- Download many free STL files for 3D printers. Find out the best paid and free 3D models of 3D printing. Share in open source or sell your 3D print files!
- GET the DRAGONFIRE MOD NOW!: TO ENTER THE DRAGON DESIGN COMPETITION.
- Dragon Email Designer 3d
- Dragon Email Designer 360
- Dragon Email Designer 3 Download
- Dragon Email Designer 3d
- Dragon Email Designer 3 Free
18,436,427 likes 34,666 talking about this. Become the ultimate Dragon Master! Build your own city and fill it with dragons! Train your cute babies and evolve them into impressive. Explore Dragon Age Games Dragon Age: Origins Dragon Age 2 Dragon Age: Inquisition. United States Argentina Australia Austria Belgium Brazil Canada Chile China Colombia Czech Republic Denmark Finland France Germany Greece Hong Kong Hungary India Ireland Israel Italy Japan Korea Mexico Netherlands New Zealand Norway Poland Portugal Russia Saudi Arabia Singapore Slovakia South Africa Spain Sweden.
This is the PHP version of my secure form mailer script. This script has a wide range of features including: an easy to use dynamic form generation system (any number of fields, in any order), multiple recipients, multiple file attachments, optional auto reply feature, an image verification system, numerous security features (including protection against email header injection), a message template system, multiple languages, and too many other things to list. This script was designed to be easy to use, while still being extremely flexible. If you just want a simple contact form, you can set one up with just a few clicks. For those of you who need something a bit more advanced, you can completely customize script plugin to fit your needs – whether it is 5 fields or 500. A WordPress plugin version is also available. reCAPTCHA v2 support has also been added, as well as support for storing the data in a delimited file.
You can see a very basic implementation of the WordPress plugin version of this script on this site’s contact page.
Notice: WordPress Users
Languages
As of the latest release, this script contains language files for:
English, Belarussian, Brazilian Portuguese, Catalan, Czech, Danish, Dutch, Estonian, Finnish, French, German, Greek, Italian, Japanese, Norwegian Bokmaal, Polish, Portuguese, Romanian, Russian, Slovak, Slovene, Spanish, Swedish, Turkish, Vietnamese
If you would like to submit a language file please contact me.
WordPress vs PHP Versions
To make things easier to find, the two versions of this script share much of the same documentation. While the basic features are the same, there are several differences, so be sure to reference the proper page.
Table of Contents
Due to the size of this page, I have split everything up into sections:
Download
Changelog
Since both the WordPress and non-WordPress versions of this script are updated together, the changelog below reflects both versions.
- 06-04-18 – v5.81 reCAPTCHA v2 support! Notice: If using the non-standalone version, be sure to add the code from the Image Verification Method section below, into your header.
- 07-05-09 – v5.8 Added Estonian language. Added code to check for duplicate field names. Can now use commas in checkbox descs. Fixed garbled auto-reply messages. Adjusted the displaying of uploaded file names in the email message. mb_encode_mimeheader error in WP fixed. Other adjustments to email headers. Added ‘id’ declaration to select boxes. Fixed incorrect example code in the instructions. Other minor changes.
- 02-22-09 – v5.7 Fixed issues regarding the saving of attached files, data selection values not being recorded, and various minor fixes. Inline styles have been removed from the two field items that contained them.
- 10-19-08 – v5.6 Added javascript date chooser field. Added html code field. Adjustments for better character set support. Fixed bug with spaces in selrecip. Commas can now be used in check boxes, radio buttons, and select boxes (see field info below). Timestamp option added for saving to data file. New email validation code (from http://code.google.com/p/php-email-address-validation/). New language added: Vietnamese
- 09-18-08 – v5.51 Captcha now displays properly in Safari and Chrome. All of the auto-reply issues should now be resolved. Few changes to headers for compatibility.
- 08-24-08 – v5.5 Fixed various undefined index errors, code changes to improve xhtml validity, attachments can now be saved to the server (not just emailed), improved email header handling for language support, can now show url (of form) in message, fixed issue with required select boxes, added Belarussian, Czech, and Japanese languages, clickable labels for radio and checkbox items, and various other fixes.
- 05-13-08 – v5.41 Added support for saving form data to a delimited file. Fixed a few issues including the loading of reCAPTCHA files, and attachment support.
- 11-25-07 – v5.4 Added support for ReCaptcha, manual form code entry, 5 new languages (Catalan, Danish, Polish, Romanian, and Turkisk), several html and css tweaks, and other misc. updates.
- 07-27-07 v5.33 – Few minor bugs fixed. Finnish language file added.
- 07-08-07 v5.32 – Error messages affecting form alignment issue resolved. Italian and Slovak language files added.
- 06-18-07 v5.3 – ‘undefined index’ errors fixed, image verification adjustments, p tags removed from fieldsets, changes to help html validity, various other fixes.
- 05-09-07 v5.25 – ‘Thank you’ message now allows for form field inputs as well.
- 05-08-07 v5.24 – Auto-reply message now allows for form field inputs. Language selection issue resolved. str_replace errors (on certain servers) fixed. Norwegian BokmÃ¥l language file added.
- 05-01-07 – Not a version update. Greek and Swedish language files added.
- 04-18-07 v5.23 – Renamed email verification function (to fix conflicts with other scripts). The GD check is now disabled if you are not using image verification. Added two new language files – Portuguese and Russian.
- 04-18-07 – Not a version update. Brazilian Portuguese language file has been added.
- 04-03-07 v5.22 – Email generation code has been modified to try to work with more servers. French language file has also been updated.
- 03-28-07 v5.21 – Highly recommended update – Fixed an issue with the verification code not being handled properly. Nothing else has been changed.
- 03-25-07 v5.2 – Email generation improved – should work better in more email clients. Many issues with message generation and field types have been fixed. Better support added for field requirement options. CSS for various fields updated. Issue with submit button fixed. Dutch and French language files added. Checkbox and drop-down issues resolved. Email verification method improved. Undefined index errors fixed, and much more. Be sure to read the updated instructions for the field types.
- 03-13-07 v5.1 – Lots of updates: Slash escaping has been improved, p tags are now added around form elements, each form instance can have its own language setting, the language selection issue has been fixed, improved foreign character support in messages, check box handling improved, and a new optional auto reply feature has been added.
- 02-06-07 v5.0 – This is a major update from version 4, and because of this, I have completely re-written this page, and removed the old changelog to save space.
Installation
- 1) Download and uncompress dd-formmailer.zip
- 2) Upload the entire dd-formmailer directory to your server
- 4) Configure your options (explained below)
- 5) Add the form to your page (explained below)
Required Configuration
While this script is highly configurable, some of you may just want to get up and running quickly with a simple (and secure) contact form. If so, these are the minimum options you need to configure within the file:
Standalone Option
$standalone – If you plan to use this script by itself (not included from another PHP file), set this option to TRUE, and it will generate a proper html header and footer. If you want to change the basic header and footer, they are found near the bottom of this script.
Path to CSS
$path_to_css – If you are using the standalone option, enter the relative path to your CSS file so it can be declared properly in the header. For those of you including this script in another PHP file, be sure to manually add the CSS declaration in the header section of your page, like this:
<link href='(path to dd-formmailer.css)' type='text/css' media='screen' />
If you plan to use the javascript date field, you will also have to include the following line:
<script type='text/javascript' src='(location of date_chooser.js)'></script>
Language Setting
$language – The relative path to the language file you want to use.
Full URL to Script
$script_path – The full URL to dd-formmailer.php (or whatever you have renamed it to)
Full URL to Contact Page
$path_contact_page – If you are running this script in standalone mode, leave this blank. Otherwise, enter the full URL to the page that is displaying the form
Recipient Data
$recipients – If you are just sending email to a single address, enter it here. For more advanced usage such as multiple recipients, CC, BCC, etc.. more information is below
The other settings are optional, and are explained below.
Other Configuration Options
This is a listing of the other configurable options in the script. These are optional, but allow for much greater customization
Form Structure – This is where you define the fields that will be used on this form. There are a lot of options available for this, and they will be explained further down as well
Manual Form Code – This is a very advanced option that has its own section on this page.
Wrap messages – This option wraps message lines to 70 characters to comply with RFC specifications
Save attachments – If enabled, attached files will be saved to a directory on the server instead of attached to the email.
Save attachment path – Where files will be saved, if attach_save is enabled. This is the full path on the server, with a trailing slash. Directory must have write permissions. Example: /home/user/public_html/uploads/
Show required – If enabled, required fields will be marked with an asterisk
Show URL – If enabled, the URL the script is running from will be added to the message
Show IP and Hostname – If enabled, the visitor’s IP and hostname are added to the message
Special Fields – Sender name, Sender email, and Email subject – These options help generate the email headers. If you enter a field name, it will be replaced by user input from that field. For example, if you have a form field called fm_name and you use that as the Sender name option, the visitor’s name will be used as the From field in the email. You can also combine them. If you have a field called fm_firstname and fm_lastname you could enter ‘fm_lastname, fm_firstname’ – For the Sender email option, just use your email field
Max upload size – This allows you to set the maximum file size (in bytes) for attachment uploads. This option only applies if the setting is lower than the value already set in your php.ini file
Message Structure – This feature is optional. If left blank, the script will generate the email message itself, which will include all the data the visitor submits. If you choose to use this option, it will act as the message template. Simply enter your custom text, including your field names. When the message is generated, the field names will be replaced by the user input from those fields. Note: Since the script will just do a search and replace for field names, be sure they are unique enough. Example: A check for fm_message2 would also get triggered by fm_message when the script adds in the input.
Success Message – This is the text that is shown after the email has been sent. You can also use field names in this, and the user input from those fields will be used to generate the message.
Auto Reply – This is an optional feature that allows you to automatically send a pre-defined message back to those who contact you. More information on this is below
Image Verification Method – There are three choices for image verification. It can be disabled, you can use the script’s built-in system (a simple captcha – requires GD support on the server), or you can use the reCAPTCHA system (requires signing up for a free account)
NOTICE!! If using the non-standalone version of this script, (meaning you are loading the form on an existing page), you must include the following in that pages header section, if using reCAPTCHA v2:
<script src='https://www.google.com/recaptcha/api.js'></script>
Basic Method Options – If using the basic image verification method, you can choose the text and background color for the image (3 or 6 digit hex codes). By default, the script will try and choose the best file format for the verification image, but if it gives you any problems, you can manually specify the format to see what works best for your server.
reCAPTCHA Method Options – If using the reCAPTCHA image verification method, you must enter the public and private keys given to you at the reCAPTCHA website. These are used to generate the verification form.
Save Data to File – When enabled, the form input will be saved to a delimited file.
Still Send Email – When using the delimited file feature, this option determines whether or not the script still sends the email.
Data Path – The path to the file the data will be written to – relative to the script’s directory. Be sure to give this file write access.
Delimiter – Fields will be separated by this character. If this character is found in the actual data, it will be removed for simplicity.
Newlines – Newlines in input, such as text areas, will be replaced by this, to keep the data on a single line in the file.
Timestamp – Adds the date/time to the beginning of each line in your data file. This uses the PHP date format. Leave blank to disable.
Other Customizations
With the exception of the text defined in the options, all text visible to the visitor is contained within the language file.
Visual changes to the form can be made in the included CSS file. The class names used in the examples below already exist within the CSS.
Usage
If you are using the standalone option, all you have to do is open the URL to the script file in your browser.
If you are not using the standalone option, you can include the script in your existing PHP file with the following code:
<?php include('dd-formmailer.php'); ?>
Be sure to use the relative path to the script file.
Advanced Recipient Options
As mentioned above, if you want to send the messages to a single recipient, just enter the email address in the recipients option. To send to multiple recipients, separate the addresses with a | (pipe) character, and use one of the following prefixes for each: to= cc= bcc=
Examples:
You can have as many of each type (to, cc, bcc) as you like, and they can be in any order, although the first one in the list is the always the primary recipient, and must use to=
For those of you who want to let the vistor choose the recipient from a drop-down box, first you must enter selrecip in the recipients field. Then you must add a new line in the form structure box. Example:
The type must be selrecip, but you can use whatever you like as the CSS class, and label. The first item in the data parameter is the default (unselected) option. After that are the names and email addresses. You can add in as many as you like – just keep them in the proper order (name,email,name,email,etc..). Only the names are visible within the HTML for privacy reasons.
The ‘(select)’ item is the default selection, which the user must change to submit the form. You can change the ‘(select)’ text if you choose.
Advanced Form Structure
This script uses a dynamic form generation system, which means that by simply adding a new line to the form structure, you will have a new field in your form. You can have as many fields as you like, and in any order. The only field type that you must absolutely have is the verify field if you are using the image verification option. All of the fields are explained below, with examples. Separate each field type with a single newline in the form structure option. (Some of the examples below are bit long, so they are wrapped to the next line – be sure that the only newlines are after each field type when adding them to your form structure.)
These are the different parameters that apply to most of the field types (Special exceptions and parameters unique to a particular field are listed under each field type):
- type – This tells the script what type of field you are adding.
- class – The CSS class used to style the field. The classes used in the examples below already exist in the CSS file.
- label – Text that is shown next to the field.
- fieldname – The name of the form field (must be unique).
- max – Maximum number of characters allowed.
- req – (OPTIONAL) If you want to require a field, set this to true. If not, do not add it.
- default – (OPTIONAL) This allows you to specify the default value of a field.
TEXT
This is a standard text input field.
The text field type has a special parameter – ver – which can be used to verify the input. You can choose email (which checks that the input is a proper email address) or url (which checks that the input is not only a proper URL, but that it actually exists). If you do not want to use either validation option, do not add this parameter.
Examples:
DATE
This is a javascript pop-up date chooser.
This field type generates a text box with a calendar icon next to it. The user can enter a date manually, or click on the icon to see a small calendar that they can choose a date from.
To change this image, just replace calendar.gif in the script directory. Either give your file the same name, or search and replace the name in the script file.
Example:
HTML
This field type lets you insert html, or other code, anywhere in your form.
Example:
PASSWORD
This is a standard password field. It is exactly like a text field, except it shows asterisks when the user types.
The password field type also has a special parameter – confirm – which if set to true, it duplicates the password field, so that the visitor has to confirm their input. If you do not want to use this, do not add the confirm parameter.
Examples:
TEXTAREA
This is a standard text area, for multiple lines of text.
The textarea field type has a special parameter – rows which defines the number of rows in the field (required for valid html).
Examples:
WIDETEXTAREA
This is exactly the same as the standard textarea, except that it’s wider, and the label is above it instead of to the side.
Example:
* Note that the normal textarea, and wide textarea fields use a different CSS class for formatting.
VERIFY
This field is required if you are using the basic verification method. It does not apply if you are using the reCAPTCHA method. It is used for placement of the verification image (and associated text box) in the form.
Example:
FULLBLOCK and HALFBLOCK
These are not standard form fields, but simply a way you can add text to your form. The full block is as wide as a wide textarea, while the half block is aligned with other standard fields. You can use basic HTML in your text if you like.
Examples:
OPENFIELDSET and CLOSEFIELDSET
These do just what the name implies – they open and close a fieldset in your form so you can help group fields together. It also allows you to specify a legend for the fieldset (required for valid HTML).
Examples:
CHECKBOX
The checkbox field can be used to generate a single checkbox, or a group of them. The usage is a bit different than the other fields.
As you can see, the checkbox data is a comma separated list of four items per checkbox:
- fieldname – A unique fieldname for each checkbox in the form.
- text – The text shown to the right of each checkbox.
- checked – true or false. This allows you to make checkboxes checked by default.
- required – true or false. If true, it means that the user must check the box to send the message. Mainly useful for ‘check here to agree’ type situations.
*NOTE* Because this field type uses commas to separate data, if you would like a comma to be displayed in your data, simply use two. It will be replaced later in the code.
Examples
RADIO
This field generates a group of radio buttons. Radio buttons are similar to checkboxes, except that they are treated as a group, and only one option may be selected.
The req and default items are optional. req, if set to true, makes the field required. default can be set to the option number you want to be selected by default (starting at 1).
*NOTE* Because this field type uses commas to separate data, if you would like a comma to be displayed in your data, simply use two. It will be replaced later in the code.
Examples:
SELECT
The select field generates either a standard drop-down box, or a multi-select box, depending on the multi option. Option groups are supported as well.
The multi and req options are optional.
If the field is required, the first option you have in the data paramater will be the default, which tells the user they need to select one of the options. If they do not change the default option, and it is required, they will receive an error.
The data field is just a list of the options, separated by a comma. To define the start of an option group, just prefix the group name with a # as shown below.
*NOTE* Because this field type uses commas to separate data, if you would like a comma to be displayed in your data, simply use two. It will be replaced later in the code.
Examples:
FILE
The file field generates a file upload box. As with all other fields, you can add as many of these as you like, as this script supports not only attachments, but multiple attachments. The only thing to keep in mind is that you may need to find out the limit your server has set for file upload sizes.
The allowed field is optional, and lets you define a (comma separated) list of file extensions that are allowed to be uploaded. Otherwise, all file types will be allowed.
Examples:
Manual Form Code
This feature allows you to manually specify the code used to generate your form. By default, this script uses the form structure information to dynamically generate the form. While this makes it easier for most people, since they do not have to write any code, it can limit those who need a bit more flexibility in their form structure.
Important Notice: Because this method means you will be writing the form code yourself, and it will not be generated by the script, there is no way for it to automatically insert the PHP code needed to put the user’s input back into the form when there is a validation error. It is just not possible for this to be done automatically due to the nature of the option. The only way this can be accomplished is if you know enough about PHP to insert the code manually yourself. In other words, this is a very advanced option – only for those who are very familiar with HTML forms and PHP.
- 1) Customize your form using the ‘Form Structure’ option as you would normally – this is required even when using the manual code entry, as it allows for processing of the form.
- 2) Be sure you have all your options exactly as you want them, and view your newly created form page.
- 3) View the source of the page, so you can copy the generated html. The code you need is between the following lines:
- 4) You can now customize this form code however you like, as long as the core elements of the form and fields are still in place.
- 5) Enter your new code into the ‘Manual Form Code’ option. (PHP VERSION NOTICE: Depending on your form code, you may have to ‘escape’ single or double quotes, as you are assigning this code as a string value to the $manual_form_code option!)
- 6) If everything worked properly, your page will now use the custom form code. Once again, the standard form structure option is still required, as it is still for processing of the form.
You can also adjust the included CSS file to better fit your needs, or completely clear it out and manually create an entire new CSS structure for your task. Keep in mind that if you change any field items (or any options which affect the form code generation), you will have to repeat this process.
To disable the manual form code feature, just clear out the option for it.
Auto Reply Feature
The options page for each instance includes fields to define an auto reply message. This is a pre-defined message that is sent back to the visitor.
To use this option, simply enter the name, email address, subject line, and message for your auto response. To disable this feature, just leave the message field blank.
You can also use field names in the auto reply message, and the user input from those fields will be used to generate the message.
Saving Data to a File
This option allows you to save the form input in a delimited file. Please see above for a full explanation of the options.
With the PHP version of this script, the path to the data file is relative to the location of the script. Be sure to give this file write access.
Other modifications
Passing values to the form
To allow values to be passed directly to the form, all you have to do is change all references of $_POST to $_REQUEST (The REQUEST superglobal contains the values of both POST and GET items)
Prevent form data from being resubmitted upon refresh
This feature is included in the WordPress plugin version, but not in the PHP version, because of how it has to be used. To enable the feature when using the script in standalone mode, add the following code after the PHP declaration at the top of the script:
If you are not using the standalone option, you must add that code at the very top of the PHP file you are calling the script from. Add PHP tags around it if needed. Just make sure there is no extra whitespace around the PHP tags.
Modifying the script to use HII for image verification
Miro has posted instructions for users wanting to use HII: Read the comment. Notice: Modifications listed in the comments may not apply for new versions of the script.
Dragon Email Designer 3d
Using SELRECIP and BCC together
The easiest way to do this, is to find the following line in the script:
$send_status = mail($send_to, $email_subject, $msg, $headers);
If you are using SELRECIP, the message will be sent to whoever the visitor chooses. If you would also like the message to go to someone else, no matter who is chosen, just duplicate that line like so, adding in the address of the secondary recipient:
$send_status = mail('user2@domain.com', $email_subject, $msg, $headers);
Troubleshooting
Fields not working properly/Form is not displaying properly
As stated above, each field item needs to be on a single line in your form structure. Many of the examples above are long, so they do not show up on a single line. Be sure to remove any linebreaks when adding them to your form. One form field statement per line.
Verification image not showing up
The first thing to do is check to make sure your paths are set correctly in the options.
This script automatically chooses the best file type to generate the verification image. If your verification image is not displaying, the problem could be that your server will not properly generate that type of file. You can manually set this using the ‘Force image type’ option in the script. It allows you to manually specify jpeg, gif, or png.
Try all the options to see which works best for you.
Problems sending email
The most common question I receive is ‘Why am I not receiving email from the script?’
There are many reasons this can happen. The first thing to do is make sure you have access to the PHP mail function on your web server, and that there are no restrictions in place that might prevent certain features of this script from working. If you are not sure, please ask your host for information. Unfortunately, I am not able to spend the time troubleshooting general server issues for everyone.
Also try having the script send the messages to another email address (on another domain), just to be sure the problem is not with your email account.
If you believe you can use the PHP mail function and have already tried a different email address, create a small PHP file with the following contents (be sure to use your own email address):
<?php mail('you@domain.com', 'test subject', 'test message'); ?>
Open the file in your browser and then check your mail. If you did not receive the message, something is not set properly on your server, and the trouble is not with this script. Even if other mail scripts work for you, that does not mean this one will, as there are several methods to send mail in PHP.
If you do receive the message, it most likely means that your server is configured to not allow the use of the fourth parameter (extra headers) in the mail() function. To work around this, replace this line:
$send_status = mail($send_to, $email_subject, $msg, $headers);
With this:
$send_status = mail($send_to, $email_subject, $msg);
The only downside is that certain features (such as some header information, and the ability to send to multiple recipients) will be disabled. You may be able to contact your host and have them change this though. Many hosts add in this restriction for security reasons, to protect against unsafe scripts.
Lastly, some servers require an extra parameter for the mail function that specifies who the message is from. In many cases, this must be an email address on the server itself. Example:
$send_status = mail($send_to, $email_subject, $msg, $headers, '-f user@domain.com');
‘Headers already sent’ error
Another common question is the ‘headers already sent’ error message. Without getting into the details, this generally happens when something is output to the browser before a call to set_cookie, header, or a number of other PHP functions. Be sure there is no extra whitespace at the top of your file.
Mail headers showing up in message body / attachments not working
This issue can be caused if your server does not like the return/newline character set being used to end lines of the email headers. If you are experiencing this problem, try changing this line:
if (!defined('PHP_EOL')) define ('PHP_EOL', strtoupper(substr(PHP_OS,0,3) 'WIN') ? 'rn' : 'n');
To this:
if (!defined('PHP_EOL')) define ('PHP_EOL', strtoupper(substr(PHP_OS,0,3) 'WIN') ? 'n' : 'n');
If you require special SMTP settings for mail to be sent
If you have to manually specify the SMTP settings, you can do so with the following code. This is only recommended for advanced users.
(Just search for the reference to the mail() function to see where to add it)
Conclusion
Please be sure to read the entire article before asking a question. I spend a lot of time on the scripts and plugins available on this site, and it can be hard to keep up with all the requests. If you need modifications or a custom version, please contact me. Thanks for reading!
Although Python provides a mail sending interface via the smtplib
module, Django provides a couple of light wrappers over it. These wrappers areprovided to make sending email extra quick, to help test email sending duringdevelopment, and to provide support for platforms that can’t use SMTP.
The code lives in the django.core.mail
module.
Quick example¶
In two lines:
Mail is sent using the SMTP host and port specified in theEMAIL_HOST
and EMAIL_PORT
settings. TheEMAIL_HOST_USER
and EMAIL_HOST_PASSWORD
settings, ifset, are used to authenticate to the SMTP server, and theEMAIL_USE_TLS
and EMAIL_USE_SSL
settings control whethera secure connection is used.
Note
The character set of email sent with django.core.mail
will be set tothe value of your DEFAULT_CHARSET
setting.
send_mail()
¶
send_mail
(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)¶
In most cases, you can send email using django.core.mail.send_mail()
.
The subject
, message
, from_email
and recipient_list
parametersare required.
subject
: A string.message
: A string.from_email
: A string. IfNone
, Django will use the value of theDEFAULT_FROM_EMAIL
setting.recipient_list
: A list of strings, each an email address. Eachmember ofrecipient_list
will see the other recipients in the “To:”field of the email message.fail_silently
: A boolean. When it’sFalse
,send_mail()
will raiseansmtplib.SMTPException
if an error occurs. See thesmtplib
docs for a list of possible exceptions, all of which are subclasses ofSMTPException
.auth_user
: The optional username to use to authenticate to the SMTPserver. If this isn’t provided, Django will use the value of theEMAIL_HOST_USER
setting.auth_password
: The optional password to use to authenticate to theSMTP server. If this isn’t provided, Django will use the value of theEMAIL_HOST_PASSWORD
setting.connection
: The optional email backend to use to send the mail.If unspecified, an instance of the default backend will be used.See the documentation on Email backendsfor more details.html_message
: Ifhtml_message
is provided, the resulting email will be amultipart/alternative email withmessage
as thetext/plain content type andhtml_message
as thetext/html content type.
The return value will be the number of successfully delivered messages (whichcan be 0
or 1
since it can only send one message).
send_mass_mail()
¶
send_mass_mail
(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)¶
django.core.mail.send_mass_mail()
is intended to handle mass emailing.
datatuple
is a tuple in which each element is in this format:
fail_silently
, auth_user
and auth_password
have the same functionsas in send_mail()
.
Each separate element of datatuple
results in a separate email message.As in send_mail()
, recipients in the samerecipient_list
will all see the other addresses in the email messages’“To:” field.
For example, the following code would send two different messages totwo different sets of recipients; however, only one connection to themail server would be opened:
The return value will be the number of successfully delivered messages.
send_mass_mail()
vs. send_mail()
¶
The main difference between send_mass_mail()
andsend_mail()
is thatsend_mail()
opens a connection to the mail servereach time it’s executed, while send_mass_mail()
usesa single connection for all of its messages. This makessend_mass_mail()
slightly more efficient.
mail_admins()
¶
mail_admins
(subject, message, fail_silently=False, connection=None, html_message=None)¶
django.core.mail.mail_admins()
is a shortcut for sending an email to thesite admins, as defined in the ADMINS
setting.
mail_admins()
prefixes the subject with the value of theEMAIL_SUBJECT_PREFIX
setting, which is '[Django]'
by default.
The “From:” header of the email will be the value of theSERVER_EMAIL
setting.
This method exists for convenience and readability.
If html_message
is provided, the resulting email will be amultipart/alternative email with message
as thetext/plain content type and html_message
as thetext/html content type.
mail_managers()
¶
mail_managers
(subject, message, fail_silently=False, connection=None, html_message=None)¶
django.core.mail.mail_managers()
is just like mail_admins()
, except itsends an email to the site managers, as defined in the MANAGERS
setting.
Examples¶
This sends a single email to john@example.com and jane@example.com, with themboth appearing in the “To:”:
This sends a message to john@example.com and jane@example.com, with them bothreceiving a separate email:
Preventing header injection¶
Header injection is a security exploit in which an attacker inserts extraemail headers to control the “To:” and “From:” in email messages that yourscripts generate.
The Django email functions outlined above all protect against header injectionby forbidding newlines in header values. If any subject
, from_email
orrecipient_list
contains a newline (in either Unix, Windows or Mac style),the email function (e.g. send_mail()
) will raisedjango.core.mail.BadHeaderError
(a subclass of ValueError
) and, hence,will not send the email. It’s your responsibility to validate all data beforepassing it to the email functions.
If a message
contains headers at the start of the string, the headers willbe printed as the first bit of the email message.
Here’s an example view that takes a subject
, message
and from_email
from the request’s POST data, sends that to admin@example.com and redirects to“/contact/thanks/” when it’s done:
The EmailMessage
class¶
Django’s send_mail()
andsend_mass_mail()
functions are actually thinwrappers that make use of the EmailMessage
class.
Not all features of the EmailMessage
class areavailable through the send_mail()
and relatedwrapper functions. If you wish to use advanced features, such as BCC’edrecipients, file attachments, or multi-part email, you’ll need to createEmailMessage
instances directly.
Note
This is a design feature. send_mail()
andrelated functions were originally the only interface Django provided.However, the list of parameters they accepted was slowly growing overtime. It made sense to move to a more object-oriented design for emailmessages and retain the original functions only for backwardscompatibility.
EmailMessage
is responsible for creating the emailmessage itself. The email backend is thenresponsible for sending the email.
For convenience, EmailMessage
provides a send()
method for sending a single email. If you need to send multiple messages, theemail backend API provides an alternative.
EmailMessage
Objects¶
- class
EmailMessage
¶
The EmailMessage
class is initialized with thefollowing parameters (in the given order, if positional arguments are used).All parameters are optional and can be set at any time prior to calling thesend()
method.
subject
: The subject line of the email.body
: The body text. This should be a plain text message.from_email
: The sender’s address. Bothfred@example.com
and'Fred'<fred@example.com>
forms are legal. If omitted, theDEFAULT_FROM_EMAIL
setting is used.to
: A list or tuple of recipient addresses.bcc
: A list or tuple of addresses used in the “Bcc” header whensending the email.connection
: An email backend instance. Use this parameter ifyou want to use the same connection for multiple messages. If omitted, anew connection is created whensend()
is called.attachments
: A list of attachments to put on the message. These canbe eitherMIMEBase
instances, or(filename,content,mimetype)
triples.headers
: A dictionary of extra headers to put on the message. Thekeys are the header name, values are the header values. It’s up to thecaller to ensure header names and values are in the correct format foran email message. The corresponding attribute isextra_headers
.cc
: A list or tuple of recipient addresses used in the “Cc” headerwhen sending the email.reply_to
: A list or tuple of recipient addresses used in the “Reply-To”header when sending the email.
For example:
The class has the following methods:
send(fail_silently=False)
sends the message. If a connection wasspecified when the email was constructed, that connection will be used.Otherwise, an instance of the default backend will be instantiated andused. If the keyword argumentfail_silently
isTrue
, exceptionsraised while sending the message will be quashed. An empty list ofrecipients will not raise an exception. It will return1
if the messagewas sent successfully, otherwise0
.message()
constructs adjango.core.mail.SafeMIMEText
object (asubclass of Python’sMIMEText
class) or adjango.core.mail.SafeMIMEMultipart
object holding the message to besent. If you ever need to extend theEmailMessage
class, you’ll probably want tooverride this method to put the content you want into the MIME object.recipients()
returns a list of all the recipients of the message,whether they’re recorded in theto
,cc
orbcc
attributes. Thisis another method you might need to override when subclassing, because theSMTP server needs to be told the full list of recipients when the messageis sent. If you add another way to specify recipients in your class, theyneed to be returned from this method as well.attach()
creates a new file attachment and adds it to the message.There are two ways to callattach()
:You can pass it a single argument that is a
MIMEBase
instance. This will be inserted directlyinto the resulting message.Alternatively, you can pass
attach()
three arguments:filename
,content
andmimetype
.filename
is the nameof the file attachment as it will appear in the email,content
isthe data that will be contained inside the attachment andmimetype
is the optional MIME type for the attachment. If youomitmimetype
, the MIME content type will be guessed from thefilename of the attachment.For example:
If you specify a
mimetype
of message/rfc822, it will alsoacceptdjango.core.mail.EmailMessage
andemail.message.Message
.For a
mimetype
starting with text/, content is expected tobe a string. Binary data will be decoded using UTF-8, and if that fails,the MIME type will be changed to application/octet-stream andthe data will be attached unchanged.In addition, message/rfc822 attachments will no longer bebase64-encoded in violation of RFC 2046#section-5.2.1, which can causeissues with displaying the attachments in Evolution and Thunderbird.
attach_file()
creates a new attachment using a file from yourfilesystem. Call it with the path of the file to attach and, optionally,the MIME type to use for the attachment. If the MIME type is omitted, itwill be guessed from the filename. You can use it like this:For MIME types starting with text/, binary data is handled as in
attach()
.
Sending alternative content types¶
It can be useful to include multiple versions of the content in an email; theclassic example is to send both text and HTML versions of a message. WithDjango’s email library, you can do this using the EmailMultiAlternatives
class. This subclass of EmailMessage
has anattach_alternative()
method for including extra versions of the messagebody in the email. All the other methods (including the class initialization)are inherited directly from EmailMessage
.
To send a text and HTML combination, you could write:
By default, the MIME type of the body
parameter in anEmailMessage
is 'text/plain'
. It is goodpractice to leave this alone, because it guarantees that any recipient will beable to read the email, regardless of their mail client. However, if you areconfident that your recipients can handle an alternative content type, you canuse the content_subtype
attribute on theEmailMessage
class to change the main content type.The major type will always be 'text'
, but you can change thesubtype. For example:
Email backends¶
The actual sending of an email is handled by the email backend.
The email backend class has the following methods:
open()
instantiates a long-lived email-sending connection.close()
closes the current email-sending connection.send_messages(email_messages)
sends a list ofEmailMessage
objects. If the connection isnot open, this call will implicitly open the connection, and close theconnection afterwards. If the connection is already open, it will beleft open after mail has been sent.
It can also be used as a context manager, which will automatically callopen()
and close()
as needed:
Obtaining an instance of an email backend¶
The get_connection()
function in django.core.mail
returns aninstance of the email backend that you can use.
get_connection
(backend=None, fail_silently=False, *args, **kwargs)¶
By default, a call to get_connection()
will return an instance of theemail backend specified in EMAIL_BACKEND
. If you specify thebackend
argument, an instance of that backend will be instantiated.
The fail_silently
argument controls how the backend should handle errors.If fail_silently
is True, exceptions during the email sending processwill be silently ignored.
All other arguments are passed directly to the constructor of theemail backend.
Django ships with several email sending backends. With the exception of theSMTP backend (which is the default), these backends are only useful duringtesting and development. If you have special email sending requirements, youcan write your own email backend.
SMTP backend¶
backends.smtp.
EmailBackend
(host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs)¶This is the default backend. Email will be sent through a SMTP server.
The value for each argument is retrieved from the matching setting if theargument is None
:
host
:EMAIL_HOST
port
:EMAIL_PORT
username
:EMAIL_HOST_USER
password
:EMAIL_HOST_PASSWORD
use_tls
:EMAIL_USE_TLS
use_ssl
:EMAIL_USE_SSL
timeout
:EMAIL_TIMEOUT
ssl_keyfile
:EMAIL_SSL_KEYFILE
ssl_certfile
:EMAIL_SSL_CERTFILE
The SMTP backend is the default configuration inherited by Django. If youwant to specify it explicitly, put the following in your settings:
If unspecified, the default timeout
will be the one provided bysocket.getdefaulttimeout()
, which defaults to None
(no timeout).
Console backend¶
Instead of sending out real emails the console backend just writes theemails that would be sent to the standard output. By default, the consolebackend writes to stdout
. You can use a different stream-like object byproviding the stream
keyword argument when constructing the connection.
Dragon Email Designer 360
To specify this backend, put the following in your settings:
This backend is not intended for use in production – it is provided as aconvenience that can be used during development.
File backend¶
The file backend writes emails to a file. A new file is created for each newsession that is opened on this backend. The directory to which the files arewritten is either taken from the EMAIL_FILE_PATH
setting or fromthe file_path
keyword when creating a connection withget_connection()
.
To specify this backend, put the following in your settings:
This backend is not intended for use in production – it is provided as aconvenience that can be used during development.
Changed in Django 3.1:Support for pathlib.Path
was added.
In-memory backend¶
The 'locmem'
backend stores messages in a special attribute of thedjango.core.mail
module. The outbox
attribute is created when thefirst message is sent. It’s a list with anEmailMessage
instance for each message that wouldbe sent.
To specify this backend, put the following in your settings:
Dragon Email Designer 3 Download
This backend is not intended for use in production – it is provided as aconvenience that can be used during development and testing.
Django’s test runner automatically uses this backend for testing.
Dummy backend¶
As the name suggests the dummy backend does nothing with your messages. Tospecify this backend, put the following in your settings:
This backend is not intended for use in production – it is provided as aconvenience that can be used during development.
Defining a custom email backend¶
If you need to change how emails are sent you can write your own emailbackend. The EMAIL_BACKEND
setting in your settings file is thenthe Python import path for your backend class.
Custom email backends should subclass BaseEmailBackend
that is located inthe django.core.mail.backends.base
module. A custom email backend mustimplement the send_messages(email_messages)
method. This method receives alist of EmailMessage
instances and returns thenumber of successfully delivered messages. If your backend has any concept ofa persistent session or connection, you should also implement the open()
and close()
methods. Refer to smtp.EmailBackend
for a referenceimplementation.
Sending multiple emails¶
Establishing and closing an SMTP connection (or any other network connection,for that matter) is an expensive process. If you have a lot of emails to send,it makes sense to reuse an SMTP connection, rather than creating anddestroying a connection every time you want to send an email.
There are two ways you tell an email backend to reuse a connection.
Dragon Email Designer 3d
Firstly, you can use the send_messages()
method. send_messages()
takesa list of EmailMessage
instances (or subclasses),and sends them all using a single connection.
For example, if you have a function called get_notification_email()
thatreturns a list of EmailMessage
objects representingsome periodic email you wish to send out, you could send these emails usinga single call to send_messages:
In this example, the call to send_messages()
opens a connection on thebackend, sends the list of messages, and then closes the connection again.
The second approach is to use the open()
and close()
methods on theemail backend to manually control the connection. send_messages()
will notmanually open or close the connection if it is already open, so if youmanually open the connection, you can control when it is closed. For example:
Configuring email for development¶
There are times when you do not want Django to send emails atall. For example, while developing a website, you probably don’t wantto send out thousands of emails – but you may want to validate thatemails will be sent to the right people under the right conditions,and that those emails will contain the correct content.
Dragon Email Designer 3 Free
The easiest way to configure email for local development is to use theconsole email backend. This backendredirects all email to stdout, allowing you to inspect the content of mail.
The file email backend can also be usefulduring development – this backend dumps the contents of every SMTP connectionto a file that can be inspected at your leisure.
Another approach is to use a “dumb” SMTP server that receives the emailslocally and displays them to the terminal, but does not actually sendanything. Python has a built-in way to accomplish this with a single command:
This command will start a minimal SMTP server listening on port 1025 oflocalhost. This server prints to standard output all email headers and theemail body. You then only need to set the EMAIL_HOST
andEMAIL_PORT
accordingly. For a more detailed discussion of SMTPserver options, see the Python documentation for the smtpd
module.
For information about unit-testing the sending of emails in your application,see the Email services section of the testing documentation.