Home Backend Development Python Tutorial Python uses SMTP to send emails

Python uses SMTP to send emails

May 24, 2017 pm 02:23 PM

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

Python创建 SMTP 对象语法如下:

import smtplib
 
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Copy after login

参数说明:

host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:ziqiangxuetang.com,这个是可选参数。

port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下SMTP端口号为25。

local_hostname: 如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。

Python SMTP对象使用sendmail方法发送邮件,语法如下:

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

参数说明:

from_addr: 邮件发送者地址。

to_addrs: 字符串列表,邮件发送地址。

msg: 发送消息

这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。

实例

以下是一个使用Python发送邮件简单的实例:

#!/usr/bin/python
 
import smtplib
 
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
 
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
 
This is a test e-mail message.
"""
 
try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"
Copy after login

使用Python发送HTML格式的邮件

Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。具体代码如下:

import smtplib  
from email.mime.text import MIMEText  
mailto_list=["YYY@YYY.com"] 
mail_host="smtp.XXX.com"  #设置服务器
mail_user="XXX"    #用户名
mail_pass="XXXX"   #口令 
mail_postfix="XXX.com"  #发件箱的后缀
  
def send_mail(to_list,sub,content):  #to_list:收件人;sub:主题;content:邮件内容
    me="hello"+"<"+mail_user+"@"+mail_postfix+">"   #这里的hello可以任意设置,收到信后,将按照设置显示
    msg = MIMEText(content,_subtype=&#39;html&#39;,_charset=&#39;gb2312&#39;)    #创建一个实例,这里设置为html格式邮件
    msg[&#39;Subject&#39;] = sub    #设置主题
    msg[&#39;From&#39;] = me  
    msg[&#39;To&#39;] = ";".join(to_list)  
    try:  
        s = smtplib.SMTP()  
        s.connect(mail_host)  #连接smtp服务器
        s.login(mail_user,mail_pass)  #登陆服务器
        s.sendmail(me, to_list, msg.as_string())  #发送邮件
        s.close()  
        return True  
    except Exception, e:  
        print str(e)  
        return False  
if __name__ == &#39;__main__&#39;:  
    if send_mail(mailto_list,"hello","<a href=&#39;http://www.cnblogs.com/xiaowuyi&#39;>小五义</a>"):  
        print "发送成功"  
    else:  
        print "发送失败"
Copy after login

或者你也可以在消息体中指定Content-type为text/html,如下实例:

#!/usr/bin/python
import smtplib
 
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
 
This is an e-mail message to be sent in HTML format
 
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
 
try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"
Copy after login

Python发送带附件的邮件

发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
Copy after login
#创建一个带附件的实例
msg = MIMEMultipart()
#构造附件1
att1 = MIMEText(open(&#39;d:\\123.rar&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;
att1["Content-Disposition"] = &#39;attachment; filename="123.doc"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)
 
#构造附件2
att2 = MIMEText(open(&#39;d:\\123.txt&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)
att2["Content-Type"] = &#39;application/octet-stream&#39;
att2["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;
msg.attach(att2)
 
#加邮件头
msg[&#39;to&#39;] = &#39;YYY@YYY.com&#39;
msg[&#39;from&#39;] = &#39;XXX@XXX.com&#39;
msg[&#39;subject&#39;] = &#39;hello world&#39;
#发送邮件
try:
    server = smtplib.SMTP()
    server.connect(&#39;smtp.XXX.com&#39;)
    server.login(&#39;XXX&#39;,&#39;XXXXX&#39;)#XXX为用户名,XXXXX为密码
    server.sendmail(msg[&#39;from&#39;], msg[&#39;to&#39;],msg.as_string())
    server.quit()
    print &#39;发送成功&#39;
except Exception, e:  
    print str(e)
Copy after login

以下实例指定了Content-type header 为 multipart/mixed,并发送/tmp/test.txt 文本文件:

#!/usr/bin/python
 
import smtplib
import base64
 
filename = "/tmp/test.txt"
 
# 读取文件内容并使用 base64 编码
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64
 
sender = &#39;webmaster@tutorialpoint.com&#39;
reciever = &#39;amrood.admin@gmail.com&#39;
 
marker = "AUNIQUEMARKER"
 
body ="""
This is a test email to send an attachement.
"""
# 定义头部信息
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
 
# 定义消息动作
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
 
%s
--%s
""" % (body,marker)
 
# 定义附近部分
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
 
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
 
try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"
Copy after login

【相关推荐】

1. 详细介绍Python使用SMTP发送邮件实例

2. Python 使用SMTP发送邮件的代码小结

3. c#调用qq邮箱smtp发送邮件修改版代码

4. 分享Python实现SMTP发送邮件图文实例

5. php smtp发送邮件

6. Python SMTP邮件模块详解

7. python smtplib模块发送SSL/TLS安全邮件实例

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

See all articles