I have a php script that sends an email. It currently uses the php mail() function.
That function then connects to sendmail feature on the linux machine. However for this implementation we were wanting to create a php script that doesn't rely on sendmail being setup or even existing so that we can move to code to any machine and have all the functionality self contained.
First off is this even possible? I've seen a few downloadable classes online so I think that it is.
Second has anyone done this before and do you know a good class or place to start?
I do need to send attachments along with the email.
PHPMailer is a very nice library which you can use to send mails via SMTP, so you don't have to rely on sendmail. PHPMailer also provides an easy way to attach files to your email.
You may also want to consider Zend_Mail. We've been using it for awhile now without issue.
There are lots of examples out there - I use swiftmailer ... http://swiftmailer.org/ or http://code.google.com/p/swiftmailer/
example usage :
require_once 'swift/lib/swift_required.php';
$smtp = Swift_SmtpTransport::newInstance('smtp.host.tld', 25)
->setUsername(' ... ')
->setPassword(' ... ');
$mailer = Swift_Mailer::newInstance($smtp);
$message = Swift_Message::newInstance('Your subject');
$message
->setTo(array(
'user1#example.org',
'user2#example.org' => 'User Two',
'user3#exmaple.org' => 'Another User Name'
))
->setFrom(array('your#address.com' => 'Your Name'))
->attach(Swift_Attachment::fromPath('/path/to/doc1.pdf'))
->attach(Swift_Attachment::fromPath('/path/to/doc2.pdf'))
->setBody(
'Here is an image <img src="' . $message->embed(Swift_Image::fromPath('/path/to/image.jpg')) . '" />',
'text/html'
)
->addPart('This is the alternative part', 'text/plain')
;
if ($mailer->send($message))
{
echo "Message sent!";
}
else
{
echo "Message could not be sent.";
}
Related
I'm new to SO, so bear with me please. I'm fairly noobish regarding code, I'm mostly a webdesigner, not developer. But my own webdeveloper is having a hard time with this problem so I'm trying to find some help where ever I can get.
So, we got this problem on a Virtuemart shop, running version 2.5.23 of Joomla with VM 2.6.10.
Server info:
PHP Built On Linux web04 3.13.0-35-generic #62~precise1-Ubuntu
Database Version: 5.1.73-0ubuntu0.10.04.1-log
Database Collation: utf8_general_ci
PHP Version: 5.3.10-1ubuntu3.14
Web Server: Apache
WebServer to PHP Interface: apache2handler
Joomla! Version: Joomla! 2.5.23 Stable [ Ember ] 24-July-2014 14:00 GMT
So this is not sending mail anywhere. We got it on a testserver and over there, life is good. It's sending e-mail. The testserver is running PHP 5.24.
I've used this to see if this checks out:
<?php
$to = "dontsentmemail#gmail.com";
if( mail( $to , 'This is a test message.' , 'Is this working?' ) ) {
echo 'Email sent.';
} else {
echo 'Email failed to send.';
}
?>
This is working fine. And I'm about to pull out all my hair. We've tried SMTP mail handling, and again, working like a charm on the testserver but it won't work on the live site.
does anybody know if is VM/joomla is using mail() directly or maybe using JUtility::sendMail() as default, and if we can change that, to make it work? Anyone got any ideas?
EDIT
I wasn't aware Joomla already includes its own version of PHPMailer. See Lodder's answer for a better out-of-the-box solution!
Try switching to a specialist mail library, e.g. PHPMailer to send the mail, instead of php's mail function.
I too had a similar problem, emails sent but not delivered, and no bounce messages. PHPMailer managed to send email that also got delivered.
<?php
require_once('path/to/PHPMailerAutoload.php');
//Create a new PHPMailer instance
$mail = new PHPMailer();
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
// Set who the message is to be sent from
// Name is optional
$mail->setFrom('somebody#yourdomain.com', 'Joe Bloggs');
//Set who the message is to be sent to
// Name is optional
$mail->addAddress('dontsentmemail#gmail.com', 'Jane Bliggs');
//Set the subject line
$mail->Subject = 'Is this working?';
// Set plain text body
$mail->IsHTML(false);
$mail->Body = 'This is a test message.';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
I would personally use Joomla's built-in JMail class which uses PHPMailer. Have a look at the following:
$mailer = JFactory::getMailer();
$mailer->setSender('dontsentmemail#gmail.com');
$mailer->addRecipient('from#emailaddress.com');
$mailer->setSubject('Your subject');
$body = "Some email text";
$mailer->setBody($body);
$send = $mailer->Send();
if ( $send !== true )
{
echo 'Error sending email';
}
else
{
echo 'Mail sent';
}
You may want to change from#emailaddress.com to whatever suits your needs. There are also some additional features for this class which can be found on the Joomla documentation:
http://docs.joomla.org/Sending_email_from_extensions
Update:
I wasn't aware that you were using a separate PHP file. At the top of your PHP file, you will need to import the Joomla framework like so:
define( '_JEXEC', 1 );
define('JPATH_BASE', __DIR__);
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$app = JFactory::getApplication('site');
You may need to change the value for JPATH_BASE so that your script points to the root of your Joomla site, relative to where you PHP file is located.
Hope this helps
in my CRM online system I control ingoing mails with IMAP protocol.
Now I'm making sending mails with phpmailer and SMTP protocol.
Everything is ok but I have one wierd thing. How to make sent with phpmailer script mails go to "Sent" IMAP folder?
There is now a method getSentMIMEMessage in PHPMailer which returns the whole MIME string
$mail = new PHPMailer();
//code to handle phpmailer
$result = $mail->Send();
if ($result) {
$mail_string = $mail->getSentMIMEMessage();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}
I found easier way to do this.
PHPmailer prepares email as string - all You have to do is to put it into right IMAP folder.
I expanded phpmailer class with this code (since vars are protected I can't reach them):
class PHPMailer_mine extends PHPMailer {
public function get_mail_string() {
return $this->MIMEHeader.$this->MIMEBody;
}}
PHP code:
$mail= new PHPMailer_mine();
//code to handle phpmailer
$result=$mail->Send();
if ($result) {
$mail_string=$mail->get_mail_string();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}
It works well.
Well, it's pretty difficult, but can be done.
Take a look at the imap-append function.
By being connected to an IMAP stream resource, you can use the imap-append() to append your mails to the Sent folder of your IMAP account.
But reading through the comments will show you that it's a bit tedious to accomplish, but certainly not impossible - you'll probably need to code something on your own, since phpmailer doesn't support this out of the box (and will most likely be too time consuming to implement instead of making something yourself).
You need to be relaying your sent mail through the IMAP host
The IMAP host needs to support the feature (which very few do)
If either of these two points are not true, the short answer is "You can't". In short, really it's down to the mail provider, not your code.
As much as I hate M$, Exchange is one place where they really have got things right - if you are using an Exchange server, all of this is handled for you.
This works well :
Php Manual
if (!$mail->send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
} else{
//echo "Message sent!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
if (save_mail($mail)) {
echo "Message saved!";
}
}
//function
function save_mail($mail)
{
$providerMail = 'Gmail';
$providerMailSentFolder = 'Sent Mail';//You can change 'Sent Mail' to any folder
$providerMailImap = 'imap.gmail.com';//imap.one.com
$path = "{".$providerMailImap.":993/imap/ssl}[".$providerMail."]/".$providerMailSentFolder;
//Tell your server to open an IMAP connection
//using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
}
How can reply-to be set when using Swiftmailer. The docs mentioned the function setReplyTo() but without specific instructions on how to use it.
Any help will be appreciated.
I can confirm that the setReplyTo method works the same way as (for example) the setCC method.
$message->setReplyTo(array(
'person1#example.org',
'person2#otherdomain.org' => 'Person 2 Name',
'person3#example.org',
'person4#example.org',
'person5#example.org' => 'Person 5 Name'
));
For those who experienced the same confusion as me, you are not able to run $recipients->setReplyTo() on a Swift_RecipientList but you are able to do so on the Swift_Message directly:
$recipients = new Swift_RecipientList;
// this is correct
$recipients->addTo('some#email.com');
// this method does not exist so this does not work
$recipients->addReplyTo('some.other#email.com');
$message = new Swift_Message($subject, $message, 'text/html');
// you can, however, add the reply-to here like this
$message->setReplyTo('some.other#email.com');
// and of course sending the e-mail like this with the reply to works
$swift->send($message, $recipients, 'some#email.com');
Here is what I need to do. I need to be able to dynamically generate custom emails. I have been using PHP's mail() function, but I have been encouraged to try phpmailer or Zendmail. But it doesn't seem to be able to handle custom emails.
What I need to do is be able to grab values from the form and insert them into the body of the message. I've been doing:
$message = '<html><body><p>First name: ' $first . '<br/><br/>';
$message .= ...(rest of message)
Then I do:
mail($recipient, $subject, $message, $headers); using the right headers for HTML.
Is there a way to do what I want with phpmailer or Zendmail? Is there a way to do this in OOP instead that might improve on what are getting to be very lengthy pages? I'd appreciate some guidance.
Using phpmailer you could try the code below.
$message = '<html><body><p>First name: '. $first . '<br/><br/>';
$mailer = new PHPMailer();
// other fields / properties
$mailer->Subject = $subject;
$mailer->AddAddress($receipient);
$mailer->IsHTML(true);
$mailer->Body = $message;
$mailer->Send();
you'd need to set the other fields for it to work properly though.
Yes, one of the main points of having a mail library is to be able to create complex emails (more easily). I would also recommend SwiftMailer.
http://swiftmailer.org
i wanna write a script sending e-mail to my client automatically using php
How do i send it automatically, for example, if they enter their email. and click submit
i wanna send this e-mail automatically
And, second do i need smtp server on my host? can i just this in any free hosting?
Thanks you guys and im so sorry for my language
Nikky
I probably wouldn't go with using the mail function directly : too many things you have to care about...
Instead, I would recommend using some mail-related library, which will deal with a lot of things for you.
One of those (which seems to have some success nowadays -- it's being integrated in the Symfony framework, for instance) is Swift Mailer.
Of course, it might be a bit overkill for just a simple mail... But investing some time in learning how to use such a library is always worth it ;-)
PHP doesn't implement SMTP protocol (RFC 5321) or IMF (RFC 5322), or MIME like Python for example. Instead - all PHP has is a simple C wrapper around sendmail MTA.
However - with all it's drawbacks - one can still create mime messages(multipart/alternative, multipart/mixed etc) and send html and text messages and also attach files using default PHP's mail() function. The problem is - it's not straightforward. You'll end up handcrafting entire message by using "headers" mail() argument, while setting "message" argument to ''. Also - sending emails in a loop through PHP's mail() will be a performance waste since mail() opens new smtp connection for each new email.
/**sending email via PHP's Mail() example:**/
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Because of these limitations most folks end up using third party libraries like:
PHPmailer (download)
Swiftmailer
Zend_Mail
Using these libraries one can construct text or html messages with ease. Adding files also becomes an easy thing to do.
/*Sending email using PHPmailer example:*/
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "from#example.com";
$mail->FromName = "Your Name";
$mail->AddAddress("myfriend#example.net"); // This is the adress to witch the email has to be send.
$mail->Subject = "An HTML Message";
$mail->IsHTML(true); // This tell's the PhPMailer that the messages uses HTML.
$mail->Body = "Hello, <b>my friend</b>! \n\n This message uses HTML !";
$mail->AltBody = "Hello, my friend! \n\n This message uses HTML, but your email client did not support it !";
if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent.';
}
ALSO:
Q: do i need smtp server on my host? can i just this in any free hosting?
A: any shared hosting has SMTP server nowadays (sendmail/postfix).
Using built-in mail() function is not a good idea in most cases. So yes, either use the SwiftMailer or:
http://phpmailer.worxware.com/ - The PhpMailer which is in many senses is a similar implementation.