Sending mails with PHPMailer. HTML content, inline images, attachments, SMTP, cyrillic support


PHPMailer is a PHP class for sending email. It has far more funtionality compared to the regular mail() function, including attachments and inline images. It is very usefull for actions like "Contactus" forms, not allowing header injection and spamming. Supports SMTP.

How do I get this?

PHPMailer can be downloaded from the official site. This is also the place where yo can find complete documentation.

First steps

After downloading archived files, unzip them and upload to the web server. Here's a simple code forsending email:

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsMail();

$mail->AddAddress("email@example.com");
$mail->Subject = "Test 1";
$mail->Body = "Test 1 of PHPMailer.";

if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;;
}
else
{
   echo "Letter sent";
}
?>


The function $mail->IsMail(); indicates that the letter must be sent using mail() function. Other methods are:

IsSendmail - via sendmail command.
IsQmail - directly via qMail MTA.
IsSMTP - via SMTP server.

Here's a sample for using SMTP. We assume that SMTP requires authorization. If it in't nessesary, just write $mail->SMTPAuth = false;. To use a number of servers use semicolumn for delimiter.

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->SMTPAuth = true;
$mail->Username = 'smtpusername';
$mail->Password = 'smtppassword';

$mail->AddAddress("email@example.com");
$mail->Subject = "Test 1";
$mail->Body = "Test 1 of PHPMailer.";

if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;;
}
else
{
   echo "Letter is sent";
}?>

To add inforation about sender, use following functions:

$mail->From="mailer@example.com";
$mail->FromName="My site's mailer";
$mail->Sender="mailer@example.com"; // indicates ReturnPath header
$mail->AddReplyTo("replies@example.com", "Replies for my site"); // indicates ReplyTo headers

For specifying various types of recepients use these:

$mail->AddAddress("mail1@domain.com", "Recepient 1");
$mail->AddCC("mail1@domain.com", "Recepient 1");
$mail->AddBCC("mail1@domain.com", "Recepient 1");


If you need 2 or more To: addresses, just call.

Additional languages

If the message contains cyrilic or other non-latin characters like unicode, you should specify the charset used:

$mail->CharSet="windows-1251";
$mail->CharSet="utf-8";

HTML content

HTML emails are better formatted and more attractive. As there are mail clients that do not support HTML, you should provide alterntive text only content. Here's a sample:

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->SMTPAuth = true;
$mail->Username = 'smtpusername';
$mail->Password = 'smtppassword';

$mail->From="mailer@example.com";
$mail->FromName="My site's mailer";
$mail->Sender="mailer@example.com";
$mail->AddReplyTo("replies@example.com", "Replies for my site");

$mail->AddAddress("email@example.com");
$mail->Subject = "Test 1";

$mail->IsHTML(true);
$mail->Body = "<h1>Test 1 of PHPMailer html</h1><p>This is a test</p>";
$mail->AltBody="This is text only alternative body.";

if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;;
}
else
{
   echo "Letter is sent";
}
?>

Images

There are two ways to add images in the HTML content. You can specify absolute address that points image on your site. The case is by using this technique, one can track down who opens the email. That's why most emal clients do not display such images. To code around this, you can attach the image in the message and link to it by a special URI.

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->SMTPAuth = true;
$mail->Username = 'smtpusername';
$mail->Password = 'smtppassword';

$mail->From="mailer@example.com";
$mail->FromName="My site's mailer";
$mail->Sender="mailer@example.com";
$mail->AddReplyTo("replies@example.com", "Replies for my site");

$mail->AddAddress("email@example.com");
$mail->Subject = "Test 1";

$mail->IsHTML(true);
$mail->AddEmbeddedImage('logo.jpg', 'logoimg', 'logo.jpg'); // attach file logo.jpg, and later link to it using identfier logoimg
$mail->Body = "<h1>Test 1 of PHPMailer html</h1>
    <p>This is a test picture: <img src=\"cid:logoimg\" /></p>";
$mail->AltBody="This is text only alternative body.";

if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;;
}
else
{
   echo "Letter is sent";
}
?>

Attachments

You may need to attach a file to the letter. Use AddAttachment() for that purpose:

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->SMTPAuth = true;
$mail->Username = 'smtpusername';
$mail->Password = 'smtppassword';

$mail->From="mailer@example.com";
$mail->FromName="My site's mailer";
$mail->Sender="mailer@example.com";
$mail->AddReplyTo("replies@example.com", "Replies for my site");

$mail->AddAddress("email@example.com");
$mail->Subject = "Your invoice";

$mail->IsHTML(false);
$mail->AddAttachment('files/invoice-user-1234.pdf', 'invoice.pdf'); // attach files/invoice-user-1234.pdf, and rename it to invoice.pdf
$mail->Body = "Please find your invoice attached.";
if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;;
}
else
{
   echo "Letter is sent";
}
?>

 

Comments:

Shaho (10-04-2009 12:32) :
Hi,

Thx for the tips, I have used this with a form where the user can upload files to send along with the mail.

I can easily attach one file through upload and AddAttachment but It doesn't accept multiple files. And it doesn't throw error msg, the files just don't show up in the mail received.

Any Ideas?

Jacques (10-05-2009 02:15) :
Hi
I'm using phpmailer v5
I can send an email with an attachment but for some reason I can't get my second attachment to send

my browser says message was sent with no errors.

this is my code:
$mail->AddAttachment("C:/wamp_new/www/images/{$Company}/{$Store}/{$jpegname1}");
$mail->AddAttachment("C:/wamp_new/www/images/{$Company}/{$Store}/{$jpegname2}");

When I swop the two around so thet jpegname2 attaches first then I get jpegname2 in my email
So the problem is not in my coding
Please help

Jaques (10-05-2009 19:05) :
There is a bug fix for phpmailer v5 to attach more than one file

http://sourceforge.net/forum/forum.php?thread_id=3176187&forum_id=81620

Good luck

uros (30-05-2009 20:56) :
i am sure this will sound incredibly stupid, but i know nothing about php. i change all the fields that need changing so that mail arrives in my inbox. but i do not know what i have to do to change that "This is test" in body and subject. How do I make it say whatever site visitor write in contact form?
once again, sorry if it is stupid questin, i'm sure it is very simple, just i'm going crazy with this for a couple of days now...

bankim rana (software engg From JustDial Pvt. Ltd.) (22-07-2009 14:38) :
I have used above code to send image and attachment but I could not get any attachment or image in mail. please give correct example for it

jpa (10-09-2009 18:08) :
Short answer to uros:

$mail->Subject = $_POST['subject'];
$mail->Body = $_POST['msg'];

'subject' and 'msg' should match the name parameters you have in the form input tags.

JSI (09-10-2009 23:24) :
I have my PHPMailer scripts working great, but I need to turn off the attachemnts when it sends the response to the person that filled out the form and added the attachments. In other words everything works fine, but the sender does not need to receive the attachments, but I cannot figure out how to turn off that one feature without affecting the attachements that still need to go to the receipient.

NIM (04-11-2009 20:43) :
I have the same problem as uros, tried using

$mail->Body = $_POST['msg'];

but only the input called "msg" got sent and not the rest of the form.

How do I send all items on the form?

Please help

bobi (04-11-2009 22:24) :
@NIM Try this one:

foreach ($_POST as $k=>$v) {
$mail->Body = "\n$k: $v";
}

Jacques (09-02-2010 04:59) :
Hi
I can do this
$mail->IsHTML(true);
$mail->AddEmbeddedImage('logo.jpg', 'logoimg', 'logo.jpg'); // attach file logo.jpg, and later link to it using identfier logoimg
$mail->Body = "<h1>Test 1 of PHPMailer html</h1>
<p>This is a test picture: <img src=\"cid:logoimg\" /></p>";

No Problem

But I want to know how does one link href the AddEmbeddedImage
I tried this
"<a href=\"skype:myskypename?call\"><img src=\"www.myurl.co.za/images/skype_logo_smaller.png\" style=\"border: none;\" width=\"113\" height=\"50\" alt=\"Skype Us\" /></a>";
but there is no href link
only the image
Does any one know solution

Jacques (09-02-2010 17:11) :
I just tested it in Outlook
In Outlook the link works but no image
In Gmail the Image shows but no hyperlink
Does anyone know the solution to this please.

Jacques (09-02-2010 21:40) :
I just tested it in Outlook
In Outlook the link works but no image
In Gmail the Image shows but no hyperlink
Does anyone know the solution to this please.

Pemi (08-03-2010 11:03) :
I think this is how various system handle an unknown protocol.. try using href=\"callto://YourSkypeName\" instead of using a skype:...

Pemi (08-03-2010 11:05) :
try using callto:skypename instead of skype:skypename?call

Neeraj (16-03-2010 14:48) :
"Error sending: Language string failed to load: instantiate"

I am getting this error.

Anyone can help me??

Thanks in advance.

Calvin Omari (19-04-2010 13:00) :
Hi,
Can somebody help me am getting this error
Message was not sent.Mailer error: Could not instantiate mail()
This is the test am using and getting the error
---------------------------------------
<?php
require("class.phpmailer.php"); // First we require the PHPMailer libary in our script
$mail = new PHPMailer(); // Next we create a new object of the PHPMailer called $mail

$mail->From = "calvinebarongo@gmail.com"; // this is the From adress (the adress the email came from)
$mail->FromName = "Calvin Omari";

$mail->AddAddress("calvinebarongo@yahoo.com"); // This is the adress to witch the email has to be send.

$mail->Subject = "First PHP Email message"; // This is the subject of the email message.

$mail->Body = "Hi! \n\n This is my first e-mail sent through PHP."; // This is the actual email message

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.';
}
?>
---------------------------------------

bobi @...Calvin Omari (21-04-2010 00:39) :
Why don't you try using SMTP as described in the article. Your hosting provider might have removed the mail() function.

Gaurav Sharma (04-06-2010 17:16) :
Great Job.....

ravi (22-06-2010 07:39) :
can someone help me i am writing html code in seprate template file but image is not showing though it is attached in email. i am using smarty. please help me!!

femi (28-07-2010 14:39) :
Hi can any one help me to fixed this problem:
could not instantiate mail function

John (29-07-2010 19:42) :
Thanks! this helped a lot

KP (28-08-2010 09:21) :
Hi this is great artical and i have some problem regarding using PHPmailer, what happening is i m using SMTP server, the problem is when i give proper authintication as needed still it gives me error as SMTP:Receipent failed. like that... please guide me.. if any one can thanks in advance....

Ann (19-11-2010 15:58) :
$mail->From = "mail@address";
is showing error
ie it is only displaying root@localhost from phpmailer class
can you help me to fix this problem

hardison (30-11-2010 13:00) :
Hello, I've installed WAMP server in my PC. Its path is F:/WAMP. I downloaded and extracted the contents of PHPMailer. Where exactly inside WAMP should i place these extracted contents???

Eduardo Dx (22-12-2010 15:02) :
Thank you. It helped a lot. =D

Esa Rantanen (21-01-2011 13:30) :
Thank you for this article, especially that $mail->AddEmbeddedImage part...

Jose (24-02-2011 14:43) :
Hello,

thank you, I tried to attach an image on my email and it worked fine!
I just have one doubt.
Could we add an image onto our email without having to attach it?.

Thanks in advance.
Regards

Khoi (04-04-2011 09:47) :
Hi!

Is that possible to embed more than 2 images using this $mail->AddEmbeddedImage. If so, please show me how.

Thanks

plrsifu.com (11-06-2011 19:50) :
this was terrific, works exactly lije it should thanks for this tutorial.

piyush Rastogi (15-09-2011 10:33) :
Hello sir

R u show mail code for user. so thnx for it but i have a problem in this code ...
u r use class.phpmailer.php file but not show this file download option or code .. so i m suggested u that if u r show it then your code run successful on web server otherwise show error ....

Henry (20-09-2011 15:04) :
I am not sure why there are no comments so far coz you are the only one i can find on the google how is able to solve my file attachment problem, keep the good work up and i will be visiting your site frequently.
:-)

Sam (22-09-2011 02:50) :
Very useful. I was looking for how to use php Mailer class. I found right content.

Harish (26-09-2011 15:30) :
I was getting A unwanted char in email content.I set charste to utf-8.Its works fine in my development server not in production server.

Any thing need to set?

Thanks

sukedhar reddy (09-12-2011 10:31) :
thank you.

Topman (25-02-2012 07:21) :
Nice help. Thanx.

Here are some solutions to some problems I found in the comments:

Problem: cannot instantiate ...
Solution: Ensure you have the right path the the phpmailer.class.php, i.e, path/to/phpmailer.class.php.

Problem: Picture not showing in email.
Comment: Some clients do not show pictures in thier mails.

Problem: WAMP
Solution: locate it in your f:/wamp/www/yoursitefolder/

Problem: Add picture, not as attachment.
Solution: Include the picture in the body of the mail - <img src='path/to/image.type' />. Remember to turn on IsHTML(true).

fashNet (05-03-2012 11:07) :
Hi am quite new to php and i will like some help arranging the code, its the whole code writting in one file page

Peter (19-03-2012 18:06) :
I tried to run some code from this site, but nothing worked until I configure XAMPP server with Mercury and gmail account. Only after that it worked.

This link can help to people, who use XAMPP:

http://www.danieltmurphy.com/setting-up-mercury-smtp/

Ahmad Sayeed (05-10-2014 18:34) :
Thanx i was trying from last 3 days and its helped me . thank you

Back to articles list

This page was last modified on 2024-03-19 03:36:46