How Ti HTML Email
How Ti HTML Email
Images can be displayed within HTML email without physically inserting them.
This keeps email size down because the images do not travel with the email. Thus, there is less chance of getting
trapped in email filters when filtering rules consider the size of the email.
Images are downloaded only when the email is opened for reading or, sometimes, when the email is in the preview
pane.
The idea is simple. The way to make an HTML email like that is the way a web page is made.
The software that sends the email must, of course, be able to send HTML email. And there are a few other
considerations:
1. All image tag src attributes must have absolute http://... URLs as their values.
2. Some email reading software can not render HTML email, some only understand basic HTML tags, and
others interpret certain HTML tags differently than a browser would. Very few email reading software
renders HTML email as well as a browser would a similar web page.
Keep the HTML as simple as possible for the visual representation you are striving for.
In a moment, I will show you how to automatically insert the tags of newly uploaded images into outgoing email. But
first, let's see several methods of manually create an HTML email with an image visually embedded.
Let's use this image, caption, and paragraphs as our example:
Top of Form
Bottom of Form
The above uses only P, IMG, and BR tags. It's the most simple HTML one can use to insert an image with caption.
Next, let's see how one would center the image and caption on the page. Let's also reduce the size of the caption
text.
Top of Form
Bottom of Form
The above should work with most email readers that understand HTML. The DIV tag centers the image and the
caption (the centering stops where the cancel </DIV> tag is at), and the style attribute in the SPAN tag (with a
corresponding cancel </SPAN> tag) specifies a smaller font size.
Notice that an inline style was used to make the caption text smaller instead of a FONT tag. That's because FONT is
deprecated and, unlike browsers that started life recognizing FONT, email readers don't need to be backward
compatible.
Now, let's get more complicated and float the image and caption to the left side of the window and have the
paragraph after the picture printed to the right of the image. If the paragraph after the picture were large enough, it
would wrap under the picture after the space on the right is used up.
Top of Form
Bottom of Form
It is a bit much to expect all email readers to know how to float something to the left. But some will do it just fine.
Those that don't understand "float:left" will most likely begin the following paragraph below the picture, which may be
an acceptable degradation.
Now that you know several ways to display an image within an HTML email, I'll show you how to automatically insert
the tags of newly uploaded images.
The software to do the job is Master Form V4.
I'll use the most complicated method above as the base for the following examples. You'll be able to change the
template as desired.
The upload form will have 4 fields to be filled in:
1. Location of file to upload. (assuming field name="iupload")
2. The image width (optional, see note). (assuming field name="iwidth")
3. The image height (optional, see note). (assuming field name="iheight")
4. The caption to be printed with the image. (assuming field name="icaption")
Note: If the image width and/or height is not specified in the form, remove those two attributes from the email
template's IMG tag so no height or width is specified. (The email template is presented further below.) Specifying an
empty or non-number value for height or width might, with some email readers, translate into the number zero. A
height or width of zero would make the image invisible.
The form will also have 3 hidden fields:
1. Where to find the file with instructions where to store the uploaded image. (name="uploadedfilesaveinfo")
2. Where to find the email template. (name="emailtemplate")
3. Where the browser goes after the upload is complete. (name="redirect" or name="flowto")
The image must be stored in a publicly accessible directory. Publicly accessible means browsers can read files in it
without providing a password. Let's assume the file with instructions where to store the uploaded image is:
Top of Form
Bottom of Form
The above says the form field name="iupload" specifies the uploaded file name and to store the uploaded file in the
"/path/to/document/root/images" directory. That would be the complete directory path of the document root plus the
name of the subdirectory to store the images at, "images" in this case.
(The document root directory is the directory where browsers find your default home page. If you don't know the path
to your document root, Master Pre-Installation Testercan help, or you can ask your hosting company.)
When the image directory is a subdirectory of the document root named "images," the URL to the image directory will
be "http://example.com/images" (substitute domain name for your own).
Now, knowing the form field names, where the image will be stored, and the image subdirectory URL, we can
construct an email template. Here is an example:
Top of Form
Bottom of Form
If you won't be asking for the width and height of the image on the upload form, remove those attributes from the
email template.
As you can see, the file is uploaded, stored on the server, and an email with live information created from the
template. Open it in your email reader and, yep, you have an email with an image displayed within it — assuming you
have a capable email reader, of course.
It does exactly what you want it to do.
Will Bontrager
Please note: All information presented "as is". Click here for expert advice.
Our first example will create a basic email message to "John Doe" and send it through
your Google Mail (GMail) account.
To add attachments to an email, you will need to use the MultiPartEmail class. This class
works just like SimpleEmail except that it adds several overloaded attach() methods to
add attachments to the email. You can add an unlimited number of attachments either
inline or attached. The attachments will be MIME encoded.
The simpliest way to add the attachments is by using the EmailAttachment class to
reference your attachments.
In the following example, we will create an attachment for a picture. We will then attach
the picture to the email and send it.
import org.apache.commons.mail.*;
...
import org.apache.commons.mail.*;
...
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new
URL("http://www.apache.org/images/asf_logo_wide.gif"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Apache logo");
attachment.setName("Apache logo");
Sending HTML formatted email is accomplished by using the HtmlEmail class. This class
works exactly like the MultiPartEmail class with additional methods to set the html
content, alternative text content if the recipient does not support HTML email, and add
inline images.
In this example, we will send an email message with formatted HTML content with an
inline image.
import org.apache.commons.mail.HtmlEmail;
...
The previous example showed how to create a HTML email with embedded images but
you need to know all images upfront which is inconvinent when using a HTML email
template. The ImageHtmlEmail helps you solving this problem by converting all external
images to inline images.
import org.apache.commons.mail.HtmlEmail;
...
The JavaMail API supports a debugging option that will can be very useful if you run into
problems. You can activate debugging on any of the mail classes by calling
setDebug(true). The debugging output will be written to System.out.
Authentication
If you need to authenticate to your SMTP server, you can call
the setAuthentication(userName,password) method before sending your email. This
will create an instance of DefaultAuthenticator which will be used by the JavaMail API
when the email is sent. Your server must support RFC2554 in order for this to work.
You can perform a more complex authentication method such as displaying a dialog box
to the user by creating a subclass of the javax.mail.Authenticator object. You will
need to override the getPasswordAuthentication() method where you will handle
collecting the user's information. To make use of your new Authenticator class, use
theEmail.setAuthenticator method.
Handling Bounced Messages
Normally, messages which cannot be delivered to a recipient are returned to the sender
(specified with the from property). However, in some cases, you'll want these to be sent
to a different address. To do this, simply call
thesetBounceAddress(emailAddressString) method before sending your email.
Technical notes: When SMTP servers cannot deliver mail, they do not pay any attention to
the contents of the message to determine where the error notification should be sent.
Rather, they refer to the SMTP "envelope sender" value. JavaMail sets this value
according to the value of the mail.smtp.from property on the JavaMail Session.
(Commons Email initializes the JavaMail Session using System.getProperties()) If this
property has not been set, then JavaMail uses the "from" address. If your email bean has
the bounceAddress property set, then Commons Email uses it to set the value
ofmail.smtp.from when the Session is initialized, overriding any other value which might
have been set.
Note: This is the only way to control the handling of bounced email. Specifically, the
"Errors-to:" SMTP header is deprecated and cannot be trusted to control how a bounced
message will be handled. Also note that it is considered bad practice to send email with an
untrusted "from" address unless you also set the bounce address. If your application
allows users to enter an address which is used as the "from" address on an email, you
should be sure to set the bounce address to a known good address.
Hi,
I am using PEAR mail system to send authenticated mails.I need to send HTML mails that has
alinks.It was working fine before i started using PEAR mail.Now i am not able to send HTML mails.
$body = <<<EOD
Hiya $username
Latest Haves
<a
href="http://www.exmaple.com/product/have/64/Titan+Fast+Track+SunGlass">T
itan Fast Track SunGlass</a>
EOD;
<?
include('Mail.php');
include('Mail/mime.php');
$body = $mime->get();
$headers = $mime->headers($headers);
Please note a version of this article is published at SitePoint which includes links to related articles
on their site. This article has been online since 2004.
Changes to this article are noted at the bottom of this article.
This article brings you up to date on how best to code HTML email so that it will display well in most
email software. It provides an exhaustive overview of how to code html email newsletters (even in
Outlook) with links to free html email templates, CSS compatability tables, services that test your
html email, and much more. This article strives to provide a comprehensive overview of all possible
resources online compared to other articles on this topic which may be vendor-specific or focus on
one aspect of how to code html email, for example, testing CSS styles across email software clients.
Here are some quick links if you only need specific information from this article:
• The Building Blocks
• Step 1: Use HTML Tables for Layout
• Step 2: Add in CSS Styles
• Step 3: Add HTML Email Best Practices
• Step 4: Code for GoogleMail, LotusNotes, and Outlook 2007
• FAQs: Create HTML Email in Outlook, Background Images, Create Anchor Links in Email, Add
Video to HTML Email
• “How to Code HTML Email” Slide Presentation
• Where to Learn More about Coding HTML Email, Including Free HTML Email Templates
• Changes to this article
My presentation also included a one-sheet with resources for coding HTML email newsletters.
Where to Learn More
Besides this article, these online resources should be very helpful:
Email Standards Project
http://www.email-standards.org/
Probably the best start point for understanding exactly how different email software complies with
HTML and CSS. They also maintain an acid test they use to compare compliance across email
software. And you can participate to help improve standards.
Free HTML Email Templates
http://campaignmonitor.com/resources/templates.aspx
http://www.mailchimp.com/resources/html_email_templates/
Both email delivery services actively test their templates over time with different email software.
However, there are subtle differences to note. Campaign Monitor has its STYLE declaration within
the HEAD tag while Mail Chimp does not. Be sure to test your final HTML code with whatever
services are used by recipients in your email list.
Plain Text Email Design Guidelines
http://www.campaignmonitor.com/resources/plain-text-templates.aspx
This article has a number of simple ways to make text emails easier to scan.
Blocked Email Images
http://www.clickz.com/showPage.html?page=3413471
http://www.campaignmonitor.com/blog/archives/2005/11/email_design_guidelines_for_20.html
From 2004, the ClickZ article shows how major email software compares for blocked images and
preview panes. The Campaign Monitor article goes into greater detail with actual examples and ideas
how to combat default image off rendering of your emails, as well as designing your email to look
okay in preview panes.
Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007
http://msdn.microsoft.com/en-us/library/aa338201.aspx
The official Microsoft description of what Outlook 2007 will and will not render for HTML and CSS.
Includes a link to a validator that works in Dreamweaver, as well as Microsoft editing tools.
A Guide to CSS Support in Email
http://www.campaignmonitor.com/blog/archives/2007/04/a_guide_to_css_support_in_emai_2.h
tml
Campaign Monitor, an email service provider, has taken Xavier Frenette’s excellent work
documenting CSS performance in a few email clients and expanded it to include Gmail, Hotmail,
Yahoo! and Windows Live Mail, as well as for the PC they cover Outlook 2003 and Outlook Express,
Lotus Notes, and Thunderbird and for the Mac they cover Mac Mail, Entourage, and Eudora.
MailChimp Email HTML Coding/Delivery Guide
http://www.mailchimp.com/resources/email_marketing_guide.phtml
Lots of great information about all aspects of html email, including how spam filters work.
CSS Support in HTML Emails of Hotmail, Yahoo! Mail, and Gmail by Xavier Frenette
http://www.xavierfrenette.com/articles/css-support-inwebmail/
This is excellent research and style by style results that show how these three webmail services
display CSS.
Secrets of HTML Email Series
http://www.graphics.com/modules.php?name=Sections&op=listarticles&secid=16
Some of this information is old but they have a good piece on Lotus Notes.
Lotus Notes Trial Software
http://www-128.ibm.com/developerworks/lotus/downloads/
Free downloads of their latest software if thoroughly testing an email with the Notes client software
is needed.
HTML Email and Web Page Testing Services
http://www.mailchimp.com MailChimp Inbox Inspector
http://www.campaignmonitor.com/testing/ Browsercam also has updated their service to display
your pages at a variety of screen resolutions.
https://browserlab.adobe.com/ Adobe BrowserLab currently is free and available anywhere with a
modern browser. It’s easy to use and displays the full range of bad browsers, specifically, IE6 and
IE7. But it also shows Chrome, Firefox, and Safari.
http://www.browsercam.com
http://www.litmusapp.com
Test compatiblity of your web pages with a variety of web browsers and operating systems. For email,
Browsercam simply shows you all the warts in your html code, even though your email might work
fine in Notes, Google Mail, and other difficult email software environments. Litmus shows how your
email appears in email software.
Best Practices For Bulletproof E-Mail Delivery
http://www.smashingmagazine.com/2007/10/16/best-practices-for-bulletproof-e-mail-delivery/
Excellent overview with some interesting ideas, resources, and details, for example, sending emails
on Tuesdays and Wednesdays from 2-3 p.m. That mirrors my experience for lists with business email
addresses (people come back from lunch and do email before meetings or getting back to work). The
best way to ensure delivery, however, is to use email inspection services provided by email delivery
vendors: it’s their job to keep up with what works best to deliver emails.
Testing Internet Explorer 6 Web Browser
Microsoft’s Expression Web SuperPreview lets you see how your email (or web pages) look in
software that uses the Microsoft web browser engine. Unfortunately, the Preview portion is not free.
You have to buy the whole package of Expression Web 3 software. Adobe’s Browserlab site is free and
might be a better option to check small changes and validate your html email displays fine.
Standalone Internet Explorer 6 Web Browser
http://tredosoft.com/Multiple_IE
This free software lets you run install and run IE6 and IE7 without causing conflicts. With Vista and
now Windows 7, this only works at installing IE6 because Windows only lets you have one IE
running at a time. Better to use BrowserLab to test against email clients that use the IE6 or IE7 html
rendering engine. Also, Microsoft’s Expression Web Super Preview is an easier and better option for
the future.
Changes to This Article
This article has been published and maintained since 2004. Here are the most recent changes:
• Updated references to background images to include a Campaign Monitor solution to the
background problem with Outlook 2007 and 2010 and GMail, Add a Background Image to your
Email in Two Simple Steps. (July 15, 2010)
• Embedded slides from a presentation I gave recently on How to Code HTML Email Newsletters.
It included a one-sheet with resources for coding HTML email newsletters. (June 15, 2010)
• Based on a comment, clarified the reason you might see CSS styles above the BODY tag open in
some email templates. The email delivery service that provides the templates moves these styles
down into inline styles as part of the delivery process. Added link to Best Practices For
Bulletproof E-Mail Delivery article in the Learn More section directly above. (May 26, 2010)
• Added link to Microsoft’s Expression Web SuperPreview software that shows how your html
email looks in older email software that uses the Microsoft web browser engine. (February 15,
2010)
• Added link to Adobe’s BrowserLab online service that, like BrowserCam, lets you see how your
web page (in this case, an html email) displays in older browser technology like IE6 and IE7. This
is useful for sending HTML email to older AOL email clients. Also added the FAQ about how to
add video to HTML email. (November 13, 2009)
• Added intra-page links to help people who arrive here from search engines. Also added link to
MailChimp’s HTML Email Inbox Inspector service. Added FAQs. (January 23, 2009)
• Updated link to MailChimp’s free HTML templates. Their URL changed without any automated
redirection. (February 23, 2009)
Share This Story:
|More
Related Stories
How to Add Background Images to Email Newsletters
How To Code HTML Email Newsletters: New Version Posted
How HTML Code Affects E-Mail Deliverability
Upgrade Your Organization’s Image with Slick HTML Newsletters
Windows XP SP2 Automatically Removes HTML Email Graphics
Outlook is Broken, Let’s Fix It
25 Questions Before You Send Email Offers and Newsletters
LikeDislike Communi Disqu
ty s
•
Add New Comment
Post as …
Showing 25 comments
Popular now
• Just wanted to say thanks for the great article. I'm coding some HTML emails for my site and my two big
gotchas that caught me: STYLE section in Gmail, and Floats in Outlook. Bleh.
• 1 person liked this. Like Reply
•
• Your welcome. And thanks for writing up what got you stuck. It helps when I rewrite the article.
• Like Reply
•
• Hi there,
I am having trouble with a newsletter format that has a table of contents. The table of contents works in web-based
email programs, but not Mac Mail.
Any help anyone can give, please do!
Melissa
[email protected]
• Like Reply
•
• fucking rubish
• Like Reply
•
• I am trying to find someone to write a script or a software that will embed a clients account number in each
story we publish. ie. The story link is http://www.eubankers.net/page.... - I need it to auto pick up the subscriber
email or account number from one source and drop it into each of the stories we send out to them. This ensures that
they don't have to login to read our news. Any thoughts would be most appreciated.
• Like Reply
•
• File > Insert Attachment > Insert As Text works just fine however :)
• Like Reply
•
• Yeah, you caught me. This article documents Outlook 2003. Sorry. Thank you for pointing this out, and
for finding the solution (which helps everyone). I'll add this shortly and check this article against the latest Outlook
versions.
• Like Reply
•
• "3. Click the New button on the Create Signature pop-up and a Create New Signature pop-up appears. Give
your new signature a name and select Use this File as a Template and browse to your HTML email."
I don't get the option to 'Use this File as a Template'. I click 'New', then it gives me a dialog for the name, Okay and
Cancel are the only options I get. From here there is no sort of button that lets me insert an HTML file :(. I'm using
Outlook 2007
• Like Reply
•
Christian Vuong 2 months ago
• Hi,
Great Article. This one answered many of my problems related to HTML emails. Thanks a Lot
• Like Reply
•
• can't understand why each and every article in web tells about using padding in s... our lotus (8.5.1.) doesn't
support it - it's the same with cellspacing and partially cellpadding. Margin works, but not in s, only in divs.... And:
width in is ignored too so you have to use clear gifs in each and every empty cell.....
i'm getting nuts! and i'm a little disillusioned by Lotus 8.5.1. - have to rebuild all templates and anyway all articles in
web are not fitting to "our" internal lotus-behaviour....
• Like Reply
•
Thanks!
Paul
• Like Reply
•
• How email software handle the newsletter code when forwarding is not standardized. The only way to
begin to ensure your email looks the same or similar is to use an HTML table to wrap your email code and use HTML
tables to structure your email layout. That said, links often don't work with forwarded HTML emails, even I notice
when sent by Feedburner and other outfits you'd expect would have solved this problem reasonably well.
• Like Reply
•
• Thank you for the 'How To Code HTML Email Newsletters (All New Version)' article. I am however having
problems emailing to Hotmail accounts where the recipient receives the HTML code and not a visual HTML email
which I get in MS Entourage for Mac. Please may you advice on what I should do to over come this? Is there anyway
of bypassing the spam firewall filter which is what I think is protecting Windows Live Hotmail accounts?
• Like Reply
•
• To summarize a few emails back and forth. The problem turned out to be with Microsoft Entourage.
When Ben switched to Thunderbird to send HTML email, the problem went away. He also found that using an email
service provider was another way to get around Hotmail's spam filters.
• Like Reply
•
• Hi,
I was having a great deal of trouble with the 1px bug, and your article really saved the day. Thanks so much for this
terrific post!
• Like Reply
•
• The sentence "Putting the right after (on the same line as) the IMG tag eliminates the annoying and
mystifying 1 pixel gap" is missing a word???? .....Putting the right [SOMETHING MISSING???] after ....or do I just not
understand what this is saying!?
• Like Reply
•
• Sorry: somehow the </td> was cut from the text. I've put it back. Basically the close TD and the IMG tag
should appear on the same line to eliminate the 1 pixel gap. This gap is less prevalent today than years ago when
browsers were more primitive. But you might see it in older email software clients.
• Like Reply
•
Globalgroupbiz 6 months ago
• hi, Learn how to code HTML emails from MailChimp, a professional email ... your HTML email along with a
plain-text alternative version of your message!
• Like Reply
•
• "CSS style declarations appear below the BODY tag, not between the HEAD tags."
-- This no longer appears to be true for the Campaign Monitor templates. Has this requirement changed? The CM
templates claim to be tested in a variety of different email clients.
• Like Reply
•
• Hi,
Campaign Monitor emailed me to say they put CSS declarations above the BODY tag in their templates as a
convenience, to make them easy to find and edit. When people send their templates through Campaign Monitor, their
service moves and converts the CSS code to inline declarations. As noted in the article above, inline CSS declarations
are the safest way to get CSS to survive email software. Thanks for asking a great question.
Tim
• Like Reply
Reactions
•
• How To Code HTML Email Newsletters (All New Version) http://t.co/2vLT6wg via @RCOTweets
•
cre8it_nl 1 month ago
• How To Code HTML Email Newsletters (All New Version) http://t.co/YbTQqRD via @RCOTweets
•
• Como maquetar email newsletter, hay resources de todo aqui, esta dpm [ http://bit.ly/bSBTG1 ]
•
• How To Code HTML Email Newsletters (All New Version) | Reach Customers Online http://otf.me/4It
•
• How To Code HTML Email Newsletters (All New Version) | Reach Customers Online | Connect with Low-
Cost Tools and Kn... http://bit.ly/blr5pA
•
junysb3 3 months ago
• How To Code HTML Email Newsletters (All New Version) | Reach Customers Online | Connect with Low-
Cost Tools and Kn... http://bit.ly/bE1BDQ
•
• How To Code HTML Email Newsletters (All New Version) | Reach Customers Online | Connect with Low-
Cost Tools and Kn... http://bit.ly/blr5pA
•
• How To Code HTML Email Newsletters (All New Version) | Reach Customers Online | Connect with Low-
Cost Tools and Kn... http://bit.ly/ccLHhA
mail
(PHP 4, PHP 5)
mail — Send mail
Report a bug
Description
bool mail ( string $to , string $subject , string $message [, string $additional_headers
[, string$additional_parameters ]] )
Sends an email.
Report a bug
Parameters
to
[email protected]
[email protected], [email protected]
User <[email protected]>
User <[email protected]>, Another User
<[email protected]>
subject
message
Message to be sent.
Each line should be separated with a LF (\n). Lines should not be larger than
70 characters.
Caution
(Windows only) When PHP is talking to a SMTP server directly, if a full stop is
found on the start of a line, it is removed. To counter-act this, replace these
occurrences with a double dot.
<?php
$text = str_replace("\n.", "\n..", $text);
?>
additional_headers (optional)
additional_parameters (optional)
Report a bug
Return Values
Returns TRUE if the mail was successfully accepted for
delivery, FALSE otherwise.
It is important to note that just because the mail was accepted
for delivery, it does NOT mean the mail will actually reach the
intended destination.
Report a bug
Changelog
Version Description
Report a bug
Examples
Example #1 Sending mail.
Using mail() to send a simple email:
<?php
// The message
$message = "Line 1\nLine 2\nLine 3";
// Send
mail('[email protected]', 'My Subject', $message);
?>
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</
th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td
>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973<
/td>
</tr>
</table>
</body>
</html>
';
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <kelly@ex
ample.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]
m>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
Note:
If intending to send HTML or otherwise Complex mails, it is
recommended to use the PEAR package» PEAR::Mail_Mime.
Report a bug
Notes
Note:
The Windows implementation of mail() differs in many ways
from the Unix implementation. First, it doesn't use a local binary
for composing messages but only operates on direct sockets
which means a MTA is needed listening on a network socket
(which can either on the localhost or a remote machine).
Second, the custom headers
like From:, Cc:, Bcc: and Date: are not interpreted by
the MTA in the first place, but are parsed by PHP.
As such, the to parameter should not be an address in the form
of "Something <[email protected]>". The mail command
may not parse this properly while talking with the MTA.
Note:
It is worth noting that the mail() function is not suitable for
larger volumes of email in a loop. This function opens and closes
an SMTP socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail,
and » PEAR::Mail_Queuepackages.
Note:
The following RFCs may be useful: » RFC 1896, » RFC 2045, »
RFC 2046, » RFC 2047, » RFC 2048,» RFC 2049, and » RFC
2822.
Report a bug
See Also
imap_mail() - Send an email message
» PEAR::Mail
» PEAR::Mail_Mime
Mailparse ezmlm_hash
<?php
?>
--
Alex M.
Use This
<?php
// Fix any bare linefeeds in the message to make it
RFC821 Compliant.
$message = preg_replace("#(?<!\r)\n#si", "\r\n", $messag
e);
<?php
?>
<?php
function mail_utf8($to, $subject = '(No
subject)', $message = '', $from) {
$header = 'MIME-Version: 1.0' . "\n" . 'Content-type:
text/plain; charset=UTF-8'
. "\n" . 'From: Yourname <' . $from . ">\n";
mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $m
essage, $header);
}
?>
<?php
$emailSentTo = "";
$subjectOfEmail = "";
// The Message
$message = $GLOBALS["HTTP_SERVER_VARS"]["REQUEST_URI"];
//Cleaning Message
$message = str_replace('?','<br><hr>',str_replace('/','Fi
le used for submittimg this form: ',str_replace('=',':
',str_replace('&','<br>',$message))));
// Sending
mail($emailSentTo, $subjectOfEmail, $message, $headers);
//Thanking
echo "<script language=\"javascript\"
type=\"text/javascript\">
alert('Thank You, We will contact you shortly.');
window.location = \"http://$_SERVER[HTTP_HOST]\";
</script>
";
?>
<?php
mail($to, $subject, $message, $headers, "-
[email protected]");
?>
For example:
$cmd = "echo '$BODY_TEXT' | mutt -s '$SUBJECT' -a
'$filename_1' -a '$filename_2' '$email'";
exec ($cmd);
Anonymous 03-Jul-2009 04:22
$headers .= "Content-Type:
multipart/alternative;boundary=\"$boundary\";\n\n";
<?php
$headers = "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html;
charset=\"iso-8859-1\"\n";
$headers .= "X-Priority: 1 (Higuest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";
<?php
$Result = trim(preg_replace("/([\w\s]+)<([\S@._-]*)>/", "
$2", $Input));
?>
I'm not a PCRE guru, but this seems to work pretty good
with any number of e-mail addresses, even when the $Input
contains "mixed" address definitions (ie. some with Full
Name and some without).
Examples:
<?php
$Result = preg_replace("/([\w\s]+)<([\S@._-]*)>/", "$2",
$Input);
?>
I've just spent about four hours trying to work out what
I was doing wrong!!
Content-Type: text/xml
<?PHP
$title=$_POST['title'];
$name=$_POST['name'];
$email=$_POST['email'];
$telephone=$_POST['telephone'];
$fax=$_POST['fax'];
$address=$_POST['address'];
$country=$_POST['country'];
$comment=$_POST['comment'];
$message .= "--$mime_boundary\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "<html>\n";
$message .= "<body style=\"font-family:Verdana, Verdana,
Geneva, sans-serif; font-size:12px; color:#666666;\">\n";
<?php
$count_recip= count($recip);//where $recip represents an
array of mail-adresses, from MySql-query or otherwise
$count='0';
$headers.="Bcc: ";
while($count < $count_recip){
$headers.=$recip[$count].", ";
$count ++;
}
$headers.="[email protected]\r\n";
?>
$To = strip_tags($to);
$TextMessage =strip_tags(nl2br($comment),"<br>");
$HTMLMessage =nl2br($comment);
$FromName =strip_tags($name);
$FromEmail =strip_tags($email);
$Subject =strip_tags($subject);
$boundary1 =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$boundary2 =rand(0,9)."-".rand(10000000000,9999999999).
"-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$attach ='yes';
$end ='';
$handle =fopen($_FILES['fileatt']['tmp_name']
[$i], 'rb');
$f_contents =fread($handle, $_FILES['fileatt']
['size'][$i]);
$attachment[]=chunk_split(base64_encode($f_contents));
fclose($handle);
$ftype[] =$_FILES['fileatt']['type'][$i];
$fname[] =$_FILES['fileatt']['name'][$i];
}
}
/********************************************************
*******
Creating Email: Headers, BODY
1- HTML Email WIthout Attachment!! <<-------- H T M L
---------
********************************************************
*******/
#---->Headers Part
$Headers =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="$boundary1"
AKAM;
#---->BODY Part
$Body =<<<AKAM
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="$boundary1"
--$boundary1
Content-Type: text/plain;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$TextMessage
--$boundary1
Content-Type: text/html;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$HTMLMessage
--$boundary1--
AKAM;
/********************************************************
*******
2- HTML Email WIth Multiple Attachment <<-----
Attachment ------
********************************************************
*******/
if($attach=='yes') {
$attachments='';
$Headers =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="$boundary1"
AKAM;
for($j=0;$j<count($ftype); $j++){
$attachments.=<<<ATTA
--$boundary1
Content-Type: $ftype[$j];
name="$fname[$i]"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="$fname[$j]"
$attachment[$j]
ATTA;
}
$Body =<<<AKAM
This is a multi-part message in MIME format.
--$boundary1
Content-Type: multipart/alternative;
boundary="$boundary2"
--$boundary2
Content-Type: text/plain;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$TextMessage
--$boundary2
Content-Type: text/html;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$HTMLMessage
--$boundary2--
$attachments
--$boundary1--
AKAM;
}
/********************************************************
*******
Sending Email
********************************************************
*******/
$ok=mail($To, $Subject, $Body, $Headers);
echo $ok?"<h1> Mail Sent</h1>":"<h1> Mail not SEND</h1>";
?>
One thing that got me stuck for a few hours was trying to
figure out why the return-path was set as the user (user
running php) and not what I was setting it with the -f
option then I later found at that in order to forcefully
set the return-path the user account running the command
must be in exim's trusted users configuration! It helps
to add trusted_groups as well then everything works
fine :)
- Richard Sumilang
<?php
$subject= mb_encode_mimeheader($subject,"UTF-
8", "B", "\n");
?>
here my solution:
<?php
// hmm no better solution?
function imap8bit(&$item, $key) {
$item = imap_8bit($item);
}
// encode subject
//=?UTF-8?Q?encoded_text?=
d 25-Dec-2007 09:39
This is an example
<?php
mail("\"Zane, CEO - MegaLab.it\"
<myaddrr@mydomain>", "prova da test_zane", "dai
funziona...");
?>
[code]
$subject = mb_encode_mimeheader('ääööö test test
öäöäöä','UTF-8');
[/code]
php-version 5.2.2
<?php
function qmail_queue($to, $from, $subject, $message, $add
itional_headers = "")
{
// qmail-queue location and hostname used for
Message-Id
$cmd = "/var/qmail/bin/qmail-queue";
$hostname = trim(file_get_contents("/var/qmail/contro
l/me"));
// BEGIN VALIDATION
// e-mail address validation
$e = "/^[-+\\.0-9=a-z_]+@([-0-9a-z]+\\.)+([0-9a-z])
{2,4}$/i";
// from address
if(!preg_match($e, $from)) return false;
// to address(es)
foreach($to as $rcpt)
{
if(!preg_match($e, $rcpt)) return false;
}
// END VALIDATION
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$invoicetotal = $_POST["invoicetotal"];
$mime_boundary = "----Your_Company_Name----".md5(time());
$to = "$email";
$subject = "This text will display in the email's Subject
Field";
$message = "--$mime_boundary\n";
$message .= "Content-Type: text/plain; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "$name:\n\n";
$message .= "This email is to confirm that \"Our
Company\" has received your order.\n";
$message .= "Please send payment of $invoicetotal to our
company address.\n\n";
$message .= "Thank You.\n\n";
$message .= "--$mime_boundary\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= "<html>\n";
$message .= "<body style=\"font-family:Verdana, Verdana,
Geneva, sans-serif; font-size:14px;
color:#666666;\">\n";
$message .= "$name:<br>\n";
$message .= "<br>\n";
$message .= "This email is to confirm that \"Our
Company\" has received your order.<br>\n";
$message .= "Please send payment of $invoicetotal to our
company address.<br>\n\n";
$message .= "<br>\n";
$message .= "Thank You.<br>\n\n";
$message .= "</body>\n";
$message .= "</html>\n";
$message .= "--$mime_boundary--\n\n";
?>
Content-Transfer-Encoding: base64\n
Content-Type: application/zip; name="test_file.zip"\n
\n //<--- if this newline isn't here your data will get
cut off
DATA GOES HERE
<?php
if (!
defined('PHP_EOL')) define ('PHP_EOL', strtoupper(substr(
PHP_OS,0,3) == 'WIN') ? "\r\n" :"\n");
?>
<?php
$headers = [...] .
"Message-ID: <". time() .rand(1,1000). "@".
$_SERVER['SERVER_NAME'].">". "\r\n" [...];
?>
<?php
# From marcelo post:
function encode_iso88591($string)
{
$text = '=?iso-8859-1?q?';
}
$text .= '?=';
return $text;
}
// create email
$msg = wordwrap($msg, 70);
$to = "[email protected]";
$subject = encode_iso88591("hoydía caminé !!");
$headers = "MIME-Versin: 1.0\r\n" .
"Content-type: text/plain; charset=ISO-
8859-1; format=flowed\r\n" .
"Content-Transfer-Encoding: 8bit\r\n" .
"From: $from\r\n" .
"X-Mailer: PHP" . phpversion();
<?php
function addattachment($file){
$fname = substr(strrchr($file, "/"), 1);
$data = file_get_contents($file);
$i = count($this->parts);
<?php
if(isset($_POST['submit']))
{
// If it is an eml file
if($file_ext == '.eml')
{
// Define vars
$dir = 'eml/';
$file = $dir.basename($_FILES['upload']['name']);
$carry = 'yes';
$pattern = '^<html>';
if(((eregi($pattern, $value)))||
($carry == 'no'))
{
else
{
$headers[$eml_file_expl[0]] = $eml_file_expl[1];
$headers[$eml_file_expl[0]] .= ':'.$eml_file_expl[$i];
}
unlink($file);
return $eml_values;
else
{
?>
24-Jul-2006 03:55
<?php
function addmessage($msg = "", $ctype = "text/plain"){
$this->parts[0] ....
?>
<?php
?>
Sander
ini_set ("sendmail_from","[email protected]");
<?php
<?php
$_POST['from']
= str_replace( "\r\n", '', $_POST['from'] );
?>
function buildmessage(){
$this->message = "This is a multipart message in
mime format.\n";
$cnt = count($this->parts);
for($i=0; $i<$cnt; $i++){
$this->message .= "--" . $this->boundary .
"\n" .$this->parts[$i];
}
$this->message .= "--" . $this->boundary . "--
\n";
}
<?php
$to = '[email protected]';
$subject = 'Wakeup bob!';
$message = '<b>yo</b>, whassup?';
$headers = "From: [email protected]\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/html; charset=utf-8\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
// Send
mail($to, $subject, $message, $headers);
?>
<?php
//add From: header
$headers = "From: webserver@localhost\r\n";
//unique boundary
$boundary = uniqid("HTMLDEMO");
//send message
mail("root@localhost", "An HTML
Message", $body, $headers);
?>
Example:
If you want a user to enter his name, then allow
characters only!
If you want a user to enter his email adress, then check
if the entry is a valid email adress.
For example:
<?php
$hs_email="[email protected]";
$hs_asunto="a message for you";
$hs_contenido="beginofcontent_";
$hs_contenido.=chr(0);
$hs_contenido.="_endofcontent";
mail($hs_email,$hs_asunto,$hs_contenido);
?>
18-Apr-2005 07:20
User <[email protected]>
<?php
$message .= "Content-Disposition: inline;
filename=\"$theFile\"\n\n";
?>
Enjoy!
<?php
include("Mail.php");
$recipients = "[email protected]";
$headers["From"] = "[email protected]";
$headers["To"] = "[email protected]";
$headers["Subject"] = "Test message";
$body = "TEST MESSAGE!!!";
$params["host"] = "example.com";
$params["port"] = "25";
$params["auth"] = true;
$params["username"] = "user";
$params["password"] = "password";
<?php
function qp_encoding($Message) {
/*
[EDIT BY danbrown AT php DOT net: The
following
is a bugfix provided by (gardan AT gmx DOT
de)
on 31-MAR-2005 with the following note:
"This means: $length should not be even,
but divisible by 4. The reason is that in
base64-encoding 3 8-bit-chars are
represented
by 4 6-bit-chars. These 4 chars must not be
split between two encoded words, according
to RFC-2047.
*/
$length = $length - ($length % 4);
?>
1. make sure the email you send out have the header
"Return-Path: [email protected]\r\n",
&
"Return-Receipt-To: [email protected]\r\n"
Note that the mail will be not be store after the mail
server has redirect to your script. If you want to store
it, you need additional code in your script
Steven Lim
IT Consultant (www.Edinburgh-Consulting.com)
add a note