Latest web development tutorials

Python SMTP to send mail

SMTP (Simple Mail Transfer Protocol) that is Simple Mail Transfer Protocol, which is a set of rules for transmitting messages from source to destination, which it has to control the way the letters of transit.

python's smtplib provides a very convenient way to send e-mail. It smtp protocol for a simple package.

Python create SMTP object syntax is as follows:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameter Description:

  • host: SMTP server host. You can specify a host ip address or domain name such as: w3cschool.cc, this is an optional parameter.
  • port: If you provide a host parameter, you need to specify the port number used by the SMTP service, under normal circumstances SMTP port number is 25.
  • local_hostname: If your SMTP on this machine, you only need to specify the server address for localhost.

Python SMTP object using sendmail method of sending e-mail with the following syntax:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

Parameter Description:

  • from_addr: e-mail sender's address.
  • to_addrs: string list, send e-mail address.
  • msg: Send a message

Here we must note that the third argument, msg is a string that represents the mail. We know that a message is generally composed of a header, sender, recipient, message content, attachments, etc., send mail, pay attention to msg format. This format is smtp protocol definition format.

Examples

The following is a message sent using Python simple example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@w3big.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

We use three quotes to set up e-mail messages, e-mail standard requires threeheaders:From, To, andSubject,each information directly with an empty row split.

We are connected by instantiating objectssmtpObjsmtplib module SMTP SMTP access to, and to send the message usingsendmailmethod.

Perform the above procedure, if you install this unit sendmail, it will output:

$ python test.py 
邮件发送成功

View our inbox (usually in the trash), you can view the e-mail message:

If we do not have native access to sendmail, you can also use other mail service providers SMTP access (QQ, Netease, Google, etc.).

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host="smtp.XXX.com"  #设置服务器
mail_user="XXXX"    #用户名
mail_pass="XXXXXX"   #口令 


sender = 'from@w3big.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user,mail_pass)  
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

Using Python sent messages in HTML format

Except messages sent Python and HTML-formatted e-mail message is sent as plain text in the MIMEText _subtype set to html. Specific code as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@w3big.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.w3big.com">这是一个链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

Perform the above procedure, if you install this unit sendmail, it will output:

$ python test.py 
邮件发送成功

View our inbox (usually in the trash), you can view the e-mail message:


Python send mail with attachments

Send messages with attachments, you first create MIMEMultipart () instance, then constructed annex, if there are multiple attachments can be constructed sequentially. Finally smtplib.smtp sent.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

sender = 'from@w3big.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("本教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

#邮件正文内容
message.attach(MIMEText('这是本教程Python 邮件发送测试……', 'plain', 'utf-8'))

# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)

# 构造附件2,传送当前目录下的 w3big.txt 文件
att2 = MIMEText(open('w3big.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="w3big.txt"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"
$ python test.py 
邮件发送成功

View our inbox (usually in the trash), you can view the e-mail message:


Add a picture in HTML text

HTML text message in the general mail service providers to add outside the chain is not valid, the right to add breakthrough are shown below:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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@w3big.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("本教程", 'utf-8')
msgRoot['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)


mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.w3big.com">本教程链接</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# 指定图片为当前目录
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, msgRoot.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"
$ python test.py 
邮件发送成功

View our inbox (if in the trash may need to move to the Inbox before the normal display), you can view the e-mail message:

For more information, please refer to: https://docs.python.org/2/library/email-examples.html .