Table of Contents
Preparation
smtplib

python send email

May 28, 2017 am 10:03 AM
python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles