## Python2.x Python SMTP Sending Email
SMTP (Simple Mail Transfer Protocol) is a set of rules for transferring mail from a source address to a destination address. It controls how the message is relayed.
Python's smtplib provides a very convenient way to send emails. It provides a simple wrapper around the SMTP protocol.
The syntax for creating an SMTP object in Python is as follows:
import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Parameter Description:
* host: SMTP server host. You can specify the host's IP address or domain name, such as: .com. This is an optional parameter.
* port: If you provide the host parameter, you need to specify the port number used by the SMTP service. Typically, the SMTP port is 25.
* local_hostname: If the SMTP server is on your local machine, you only need to specify the server address as localhost.
The Python SMTP object uses the sendmail method to send emails. The syntax is as follows:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
Parameter Description:
* from_addr: The sender's email address.
* to_addrs: A list of strings, the recipient email addresses.
* msg: The message to send.
Note here the third parameter, msg is a string representing the email. An email generally consists of a subject, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the format of msg. This format is the format defined by the SMTP protocol.
### Example
The following execution example requires that your local machine has an SMTP-supporting service installed, such as sendmail.
The following is a simple example of sending an email using Python:
## Example
import smtplib from email.mime.text import MIMEText from email.header import Header sender = 'from@.com'receivers = ['429240967@qq.com']message = MIMEText('Python email sending test...', 'plain', 'utf-8')message['From'] = Header("Rookie Tutorial", 'utf-8')message['To'] = Header("Test", 'utf-8')subject = 'Python SMTP Email Test'message['Subject'] = Header(subject, 'utf-8')try: smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message.as_string())print"Email sent successfully"except smtplib.SMTPException: print"Error: Unable to send email"
We use triple quotes to set the email information. A standard email requires three header fields: **From**, **To**, and **Subject**, each separated by a blank line.
We instantiate an SMTP object _smtpObj_ from the smtplib module to connect to the SMTP server and use the _sendmail_ method to send the message.
Execute the above program. If you have **sendmail (Mail Transport Agent)** installed on your local machine, it will output:
$ python test.py Email sent successfully
Check our inbox (usually in the spam folder), and you can view the email information:
!(#)
If our local machine does not have a sendmail server, we can also use the SMTP service of other email providers (QQ, NetEase, Google, etc.).
## Example
import smtplib from email.mime.text import MIMEText from email.header import Header mail_host="smtp.XXX.com"mail_user="XXXX"mail_pass="XXXXXX"sender = 'from@.com'receivers = ['429240967@qq.com']message = MIMEText('Python email sending test...', 'plain', 'utf-8')message['From'] = Header("Rookie Tutorial", 'utf-8')message['To'] = Header("Test", 'utf-8')subject = 'Python SMTP Email Test'message['Subject'] = Header(subject, 'utf-8')try: smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, 25)smtpObj.login(mail_user,mail_pass)smtpObj.sendmail(sender, receivers, message.as_string())print"Email sent successfully"except smtplib.SMTPException: print"Error: Unable to send email"
* * *
## Sending HTML Emails with Python
The difference between sending HTML-formatted emails and plain text emails in Python is setting the _subtype in MIMEText to html. The specific code is as follows:
## Example
import smtplib from email.mime.text import MIMEText from email.header import Header sender = 'from@.com'receivers = ['429240967@qq.com']mail_msg = """
Python email sending test...
This is a link
"""message = MIMEText(mail_msg, 'html', 'utf-8')message['From'] = Header("Rookie Tutorial", 'utf-8')message['To'] = Header("Test", 'utf-8')subject = 'Python SMTP Email Test'message['Subject'] = Header(subject, 'utf-8')try: smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message.as_string())print"Email sent successfully"except smtplib.SMTPException: print"Error: Unable to send email"
Execute the above program. If you have sendmail installed on your local machine, it will output:
$ python test.py Email sent successfully
Check our inbox (usually in the spam folder), and you can view the email information:
!(#)
* * *
To send an email with attachments, first create a MIMEMultipart() instance, then construct the attachment(s). If there are multiple attachments, construct them one by one, and finally use smtplib.smtp to send.
## Example
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header sender = 'from@.com'receivers = ['429240967@qq.com']message = MIMEMultipart()message['From'] = Header("Rookie Tutorial", 'utf-8')message['To'] = Header("Test", 'utf-8')subject = 'Python SMTP Email Test'message['Subject'] = Header(subject, 'utf-8')message.attach(MIMEText('This is the Rookie Tutorial Python email sending testβ¦β¦', 'plain', 'utf-8'))att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')att1 = 'application/octet-stream'att1 = 'attachment; filename="test.txt"'message.attach(att1)att2 = MIMEText(open('.txt', 'rb').read(), 'base64', 'utf-8')att2 = 'application/octet-stream'att2 = 'attachment; filename=".txt"'message.attach(att2)try: smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, message.as_string())print"Email sent successfully"except smtplib.SMTPException: print"Error: Unable to send email"
$ python test.py Email sent successfully
Check our inbox (usually in the spam folder), and you can view the email information:
!(#)
* * *
## Adding Images in HTML Text
In the HTML text of an email, adding external links is generally invalid for email service providers. The correct way to add images is shown in the following example:
## Example
import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header sender = 'from@.com'receivers = ['429240967@qq.com']msgRoot = MIMEMultipart('related')msgRoot['From'] = Header("Rookie Tutorial", 'utf-8')msgRoot['To'] = Header("Test", 'utf-8')subject = 'Python SMTP Email Test'msgRoot['Subject'] = Header(subject, 'utf-8')msgAlternative = MIMEMultipart('alternative')msgRoot.attach(msgAlternative)mail_msg = """
Python email sending test...
Rookie Tutorial Link
Image demonstration:

"""msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))fp = open('test.png', 'rb')msgImage = MIMEImage(fp.read())fp.close()msgImage.add_header('Content-ID', '')msgRoot.attach(msgImage)try: smtpObj = smtplib.SMTP('localhost')smtpObj.sendmail(sender, receivers, msgRoot.as_string())print"Email sent successfully"except smtplib.SMTPException: print"Error: Unable to send email"
$ python test.py Email sent successfully
Check our inbox (if it's in the spam folder, you may need to move it to the inbox for normal display), and you can view the email information:
!(#)
* * *
## Using a Third-party SMTP Service
Here we use QQ Mail's SMTP service (you can also use 163, Gmail, etc.). The following configuration is required:
!(#)
QQ Mail generates an authorization code to set the password:
!(#)
QQ Mail SMTP server address: smtp.q