search
HomeBackend DevelopmentPython TutorialPython code summary for sending emails using SMTP

Python code summary for sending emails using SMTP

May 24, 2017 pm 03:33 PM
pythonsmtpsend email

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装,需要的朋友可以参考下

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
Python创建 SMTP 对象语法如下:

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

参数说明:
host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:w3cschool.cc,这个是可选参数。
port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下SMTP端口号为25。
local_hostname: 如果SMTP在你的本机上,你只需要指定服务器地址为 localhost 即可。
Python SMTP对象使用sendmail方法发送邮件,语法如下:

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

参数说明:

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"

使用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("发送失败")

或者你也可以在消息体中指定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 id="This-nbsp-is-nbsp-headline">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")

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


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

#创建一个带附件的实例
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))

以下实例指定了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")

【相关推荐】

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
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
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function