使用smtplib模块发送邮件

  在使用django/flask时,框架本身已经为我们封装好了发送邮件的函数,python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

对于smtp的使用相对来说比较简单,代码如下:

一、发送文本内容

直接使用smtplib发送文本内容,以下两步是使用smtplib发送任何形式邮件都可以遵循的。

1. 准备工作

构建邮件内容, From(发件人)、To(收件人)、Subject(邮件标题)和Text(邮件内容)。

import smtplib
import string


smtpserver = 'smtp.163.com'     # 邮件smtp的地址
subject = '这是邮件标题'         # 定义邮件的标题
sender = 'youremail@163.com'    # 发件人
receiver = 'toemail@qq.com'     # 收件人
msg = '这是一封测试邮件,由<%s>发出'%From  # 发送的邮件文本内容
msg_content = '\r\n'.join(['From:%s'%sender, 'To:%s'%receiver, 'Subject:%s'%subject, '', msg])

2. 构造SMTP对象发送邮件

smtp_server = smtplib.SMTP()       # 构造smtp服务对象,可以在构造对象时将host和port传入直接连接服务器
smtp_server.set_debuglevel(1)                  # 开启发送debug模式,把发送邮件的过程显示出来
smtp_server.connect(host=smtpserver, port='25')           # 连接邮箱服务器,端口可以不写,默认为25
smtp_server.starttls()                                             # 启动安全传输模式
smtp_server.login(FROM, 'yourpassword')                            # 登录邮箱服务器
smtp_server.sendmail(from_addr=sender, to_addrs=receiver, msg=msg_content) # 发送邮件
smtp_server.quit()                                                 # 关闭smtp服务器连接

二、使用email模块发送多样化的内容

  email模块配合smtplib进行邮件的发送和接收,包含自定义邮件的中文、主题、日期、附件等信息,具体概念及其函数参考官方文档,链接奉上https://docs.python.org/3/library/email.html#module-email
如果要使用email模块的功能,可以参考网上的以下7个例子:

1. 文件形式的邮件

import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  

sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'  

msg = MIMEText('你好','text','utf-8') # 中文需参数‘utf-8',单字节字符不需要  
msg['Subject'] = Header(subject, 'utf-8')  

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  

2. html形式的邮件

import smtplib  
from email.mime.text import MIMEText  

sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'  

msg = MIMEText('</pre>  
<h1>你好</h1>  
<pre>','html','utf-8')   

msg['Subject'] = subject   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  

3. 带图片的html邮件

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

sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'   

msgRoot = MIMEMultipart('related')  
msgRoot['Subject'] = 'test message'   

msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.  
<img alt="" src="cid:image1" />  
good!','html','utf-8')  
msgRoot.attach(msgText)   

fp = open('h:\\python\\1.jpg', 'rb')  
msgImage = MIMEImage(fp.read())  
fp.close()   

msgImage.add_header('Content-ID', '')  
msgRoot.attach(msgImage)   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msgRoot.as_string())  
smtp.quit()  

4. 带附件的邮件

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

sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'   

msgRoot = MIMEMultipart('related')  
msgRoot['Subject'] = 'test message'   

#构造附件  
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')  
att["Content-Type"] = 'application/octet-stream'  
att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
msgRoot.attach(att)   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msgRoot.as_string())  
smtp.quit()  

5. 群邮件

import smtplib  
from email.mime.text import MIMEText   

sender = '***'  
receiver = ['***','****',……]  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'   

msg = MIMEText('你好', 'text', 'utf-8')   

msg['Subject'] = subject   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  

6. 包含各种元素的邮件

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

sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'   

# Create message container - the correct MIME type is multipart/alternative.  
msg = MIMEMultipart('alternative')  
msg['Subject'] = "Link"   

# Create the body of the message (a plain-text and an HTML version).  
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"  
html = """\ 


Hi! 

       How are you? 

       Here is the <a href="http://www.python.org">link</a> you wanted. 



"""   

# Record the MIME types of both parts - text/plain and text/html.  
part1 = MIMEText(text, 'plain')  
part2 = MIMEText(html, 'html')   

# Attach parts into message container.  
# According to RFC 2046, the last part of a multipart message, in this case  
# the HTML message, is best and preferred.  
msg.attach(part1)  
msg.attach(part2)  
#构造附件  
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')  
att["Content-Type"] = 'application/octet-stream'  
att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
msg.attach(att)   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  

7. 基于ssl的邮件

import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  
sender = '***'  
receiver = '***'  
subject = 'python email test'  
smtpserver = 'smtp.163.com'  
username = '***'  
password = '***'   

msg = MIMEText('你好','text','utf-8') # 中文需参数‘utf-8',单字节字符不需要  
msg['Subject'] = Header(subject, 'utf-8')   

smtp = smtplib.SMTP()  
smtp.connect('smtp.163.com')  
smtp.ehlo()  
smtp.starttls()  
smtp.ehlo()  
smtp.set_debuglevel(1)  
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()  
展开阅读全文

没有更多推荐了,返回首页