Home > Article > Backend Development > python send email
The two main ways to send emails in python are smtplib and email Modules, the following mainly explains these two modules
#Before explaining, you need to prepare at least two test mailboxes, in which smtplib must be turned on in the mailbox settings. The protocol can be sent and received
##smtplib.SMTP( [host [, port [, local_hostname [,
time<a href="http://www.php.cn/wiki/1268.html" target="_blank">out]]]])</a>
hostis the server of the
SMTPhost, where the
163mailbox is
smtp.163.com, others can be found online,
portis the port number, the default here is
25,
local_hostnameis your host
SMTP, if
SMTPis on your local machine, you only need to specify the server address as
localhost.
timeoutis the set connection limit time. If the connection is not connected after this time, an error will occur
SMTP.
set<a href="http://www.php.cn/code/8209.html" target="_blank">_debuglevel(level)</a>: Set whether to
debug mode. The default is False, which is non-debugging mode, which means no debugging information will be output. If set to
1, it means output debugging information
- ##SMTP.connect([host[, port]])
: Connect to the specified
smtp
server. The parameters representsmpt
host and port respectively. Note: You can also specify the port number in thehost
parameter (for example:smpt.yeah.net:25
), so there is no need to give theport
parameter.
- SMTP.login(user, passw
ord
)<a href="http://www.php.cn/wiki/1360.html" target="_blank"> Log in to the server, here </a>user
is the user name of the email, but thepassword
here is not the password of your email. When you turn onSMTP
, you will be prompted to set a password, here The password is the corresponding password
##SMTP.s
- end
mail(from_addr, [to_addrs, ], msg[, mail_options, rcpt_options])
Send an email, <a href="http://www.php.cn/wiki/1048.html" target="_blank">from_addr</a> is the sender, which is your email address,
to_addris the address of the recipient, of course it can be used here Fill in multiple email accounts and send to multiple accounts. If there are multiple accounts, you need to use a list to pass parameters
##emialSMTP .quit()
- Disconnect
email
module is used to process emails Messages, including MIME and other message documents based onRFC 2822. It is very simple to use these modules to define the content of emails. The classes it includes are (more detailed introduction can be found at: http://docs.python.org/library/email.mime.html):
##class: A subclass ofemail.mime.base.MIMEBase(_
##class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]] ]- main
type, _subtype, **_params)
: This is <a href="http://www.php.cn/wiki/164.html" target="_blank">MIME</a> A base class. There is generally no need to create an instance when using it. Where _maintype is the content type, such as text or image. _subtype is the <a href="http://www.php.cn/wiki/646.html" target="_blank">minor type</a> type of the content, such as
plainor
gif
.
**_paramsis a dictionary, passed directly to Message.add_<a href="http://www.php.cn/wiki/109.html" target="_blank">head</a>er().
MIMEBaseMIMEMultipart A subclass of, a collection of multiple
:- MIME
#class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])
objects
,_subtype
default value ismixed
. boundary is the boundary ofMIMEMultipart
. The default boundary is countable. This class is used when sending attachments.
.
##class email.mime.audio.MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]])
:
MIMEAudioObject
ordinary text emails
- class email. mime.text.MIMEText(_text[, _subtype[, _charset]])
:
MIME
text object, where_text
is the email content,_subtype
email Type, can betext/plain
(ordinary text email),html/plain
(html email),_charset
encoding, can begb2312
etc.
##Ordinary textE-mail sending
- , the key is to
MIMEText中_subtype
is set to
plain. First import
smtpliband
mimetext. Create
smtplib.smtpinstance,
connectserver, send after
login, the specific code is as follows*
# 一个格式化邮件的函数,可以用来使用def _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEText('乔装打扮,不择手段','plain','utf-8') #这里text=乔装打扮,不择手段msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr) #格式化发件人msg['To'] = _format_addr(u'管理员 <%s>' % to_email) #格式化收件人msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() #格式化主题stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Send html email
MIMETextto send, but the _subType
can be set to html, the detailed code is as follows:
def _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址html="""<p><h1 style="color:red">大家好</h1></p>"""msg=MIMEText(html,'html','utf-8') #这里text=html,设置成html格式的msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr) #格式化发件人msg['To'] = _format_addr(u'管理员 <%s>' % to_email) #格式化收件人msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() #格式化主题stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Sending attachments
MIMEMultipart()instance, and then construct the attachment. If there are multiple attachments, It can be constructed in sequence and finally sent using smtplib.smtp
. The specific strength is as follows:
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEMultipart() #创建实例text=MIMEText('<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>','html','utf-8') msg.attach(text) #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open('/home/chenjiabing/文档/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8') att1["Content-Type"] = 'application/octet-stream' #指定类型att1["Content-Disposition"] = 'attachment; filename="123.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1) #向其中添加附件img_path='/home/chenjiabing/文档/MeiZi_img/full/file.jpg' #图片路径image=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image.add_header('Content-ID','<0>') #指定图片的编号,这个会在后面用到image.add_header('Content-Disposition', 'attachment', filename='test.jpg') image.add_header('X-Attachment-Id', '0') msg.attach(image) #添加附件stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Embed the picture into the text message
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEMultipart() #创建实例html="""<html><head></head><body><p>下面演示嵌入图片</p><section><img src='cid:0' style='float:left'/><img src='cid:1' style='float:left'/></setcion></body></html>"""text=MIMEText('<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>','html','utf-8') msg.attach(text) #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open('/home/chenjiabing/文档/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8') att1["Content-Type"] = 'application/octet-stream' #指定类型att1["Content-Disposition"] = 'attachment; filename="123.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1) #向其中添加附件## 创建一个图片附件img_path='/home/chenjiabing/文档/MeiZi_img/full/file.jpg' #图片路径image=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image.add_header('Content-ID','<0>') #指定图片的编号,image.add_header('Content-Disposition', 'attachment', filename='test.jpg') image.add_header('X-Attachment-Id', '0') msg.attach(image) #添加附件#创建第二个图片附件img_path_1='/home/chenjiabing/文档/MeiZi_img/full/test.jpg' #图片路径image1=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image1.add_header('Content-ID','<1>') #指定图片的编号,这个就是在上面对应的cid:1的那张图片,因此这里的编号一定要对应image1.add_header('Content-Disposition', 'attachment', filename='img.jpg') image1.add_header('X-Attachment-Id', '0') msg1.attach(image) #添加附件stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
The above is the detailed content of python send email. For more information, please follow other related articles on the PHP Chinese website!