Home > Backend Development > Python Tutorial > python send email

python send email

大家讲道理
Release: 2017-05-28 10:03:55
Original
1692 people have browsed it

pythonSend email

Preparation

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

  • ##smtplib.SMTP( [host [, port [, local_hostname [,time<a href="http://www.php.cn/wiki/1268.html" target="_blank">out]]]])</a> host is the server of the SMTP host, where the 163 mailbox is smtp.163.com, others can be found online, port is the port number, the default here is 25, local_hostname is your host SMTP, if SMTP is on your local machine, you only need to specify the server address as localhost. timeout is 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 represent smpt host and port respectively. Note: You can also specify the port number in the host parameter (for example: smpt.yeah.net:25), so there is no need to give the port 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 the password here is not the password of your email. When you turn on SMTP, 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_addr is 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

    SMTP .quit()
  • Disconnect

  • email

##emial
module is used to process emails Messages, including MIME and other message documents based on

RFC 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
    email.mime.base.MIMEBase(_
  • 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 plain or gif. **_params is a dictionary, passed directly to Message.add_<a href="http://www.php.cn/wiki/109.html" target="_blank">head</a>er().

##class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]] ]
: A subclass of
MIMEBase
    , a collection of multiple
  • MIME

    objects, _subtypedefault value is mixed . boundary is the boundary of MIMEMultipart. The default boundary is countable. This class is used when sending attachments.

  • #class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])
MIMEMultipart A subclass of
.
  • ##class email.mime.audio.MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIMEAudioObject

  • ##class email.mime. image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]])

    MIMEBinary file object. Mainly used to send pictures

ordinary text emails

  • class email. mime.text.MIMEText(_text[, _subtype[, _charset]])

    : MIME text object, where _text is the email content, _subtype email Type, can be text/plain (ordinary text email), html/plain (html email), _charset encoding, can be gb2312etc.

##Ordinary text
    E-mail sending
  • , the key is to

    MIMEText_subtype is set to plain. First import smtplib and mimetext. Create smtplib.smtp instance, connectmailsmtp server, send after login, the specific code is as follows*

# 一个格式化邮件的函数,可以用来使用def _format_addr(s):
    name, addr = parseaddr(s)    return formataddr((
        Header(name, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEText(&#39;乔装打扮,不择手段&#39;,&#39;plain&#39;,&#39;utf-8&#39;)  #这里text=乔装打扮,不择手段msg[&#39;From&#39;] = _format_addr(u&#39;Python爱好者 <%s>&#39; % from_addr)  #格式化发件人msg[&#39;To&#39;] = _format_addr(u&#39;管理员 <%s>&#39; % to_email)    #格式化收件人msg[&#39;Subject&#39;] = Header(u&#39;来自SMTP的问候……&#39;, &#39;utf-8&#39;).encode()    #格式化主题stmp=&#39;smtp.163.com&#39;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换成一个列表
Copy after login


Send html email

Still use
MIMEText

to 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, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址html="""<p><h1 style="color:red">大家好</h1></p>"""msg=MIMEText(html,&#39;html&#39;,&#39;utf-8&#39;)  #这里text=html,设置成html格式的msg[&#39;From&#39;] = _format_addr(u&#39;Python爱好者 <%s>&#39; % from_addr)  #格式化发件人msg[&#39;To&#39;] = _format_addr(u&#39;管理员 <%s>&#39; % to_email)    #格式化收件人msg[&#39;Subject&#39;] = Header(u&#39;来自SMTP的问候……&#39;, &#39;utf-8&#39;).encode()    #格式化主题stmp=&#39;smtp.163.com&#39;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换成一个列表
Copy after login


Sending attachments

To send emails with attachments, you must first create a
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, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEMultipart()   #创建实例text=MIMEText(&#39;<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>&#39;,&#39;html&#39;,&#39;utf-8&#39;)
msg.attach(text)   #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open(&#39;/home/chenjiabing/文档/MeiZi_img/full/file.txt&#39;,&#39;rb&#39;).read(),&#39;plain&#39;,&#39;utf-8&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;  #指定类型att1["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)     #向其中添加附件img_path=&#39;/home/chenjiabing/文档/MeiZi_img/full/file.jpg&#39;  #图片路径image=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image.add_header(&#39;Content-ID&#39;,&#39;<0>&#39;)   #指定图片的编号,这个会在后面用到image.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;test.jpg&#39;)        
image.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg.attach(image)    #添加附件stmp=&#39;smtp.163.com&#39;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换成一个列表
Copy after login


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, &#39;utf-8&#39;).encode(),
        addr.encode(&#39;utf-8&#39;) if isinstance(addr, unicode) else addr))

from_addr=&#39;××××××××&#39;   #你的邮箱地址from_password=&#39;×××××××&#39;   #你的密码# to_email=&#39;chenjiabing666@yeah.net&#39;to_email=&#39;××××××&#39;    #要发送的邮箱地址msg=MIMEMultipart()   #创建实例html="""<html><head></head><body><p>下面演示嵌入图片</p><section><img src=&#39;cid:0&#39; style=&#39;float:left&#39;/><img src=&#39;cid:1&#39; style=&#39;float:left&#39;/></setcion></body></html>"""text=MIMEText(&#39;<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>&#39;,&#39;html&#39;,&#39;utf-8&#39;)
msg.attach(text)   #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open(&#39;/home/chenjiabing/文档/MeiZi_img/full/file.txt&#39;,&#39;rb&#39;).read(),&#39;plain&#39;,&#39;utf-8&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;  #指定类型att1["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)     #向其中添加附件## 创建一个图片附件img_path=&#39;/home/chenjiabing/文档/MeiZi_img/full/file.jpg&#39;  #图片路径image=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image.add_header(&#39;Content-ID&#39;,&#39;<0>&#39;)   #指定图片的编号,image.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;test.jpg&#39;)        
image.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg.attach(image)    #添加附件#创建第二个图片附件img_path_1=&#39;/home/chenjiabing/文档/MeiZi_img/full/test.jpg&#39;  #图片路径image1=MIMEImage(open(img_path,&#39;rb&#39;).read())     #创建一个图片附件image1.add_header(&#39;Content-ID&#39;,&#39;<1>&#39;)   #指定图片的编号,这个就是在上面对应的cid:1的那张图片,因此这里的编号一定要对应image1.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;img.jpg&#39;)        
image1.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
msg1.attach(image)    #添加附件stmp=&#39;smtp.163.com&#39;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换成一个列表
Copy after login


The above is the detailed content of python send email. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template