使用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()  
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 导入smtplib模块和MIME模块 ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication ``` 2. 设置发件人、收件人、主题和正文 ```python sender = '发件人邮箱地址' receiver = '收件人邮箱地址' subject = '邮件主题' body = '邮件正文' ``` 3. 创建MIMEMultipart对象并设置发件人、收件人和主题 ```python message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject ``` 4. 创建MIMEText对象并设置正文 ```python text = MIMEText(body) message.attach(text) ``` 5. 创建MIMEApplication对象并设置附件 ```python with open('附件文件路径', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='pdf') attachment.add_header('Content-Disposition', 'attachment', filename='附件文件名.pdf') message.attach(attachment) ``` 6. 连接SMTP服务器并登录,发送邮件 ```python smtp_server = 'SMTP服务器地址' smtp_port = 25 # SMTP服务器端口号 smtp_user = 'SMTP服务器用户名' smtp_password = 'SMTP服务器密码' smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.login(smtp_user, smtp_password) smtp.sendmail(sender, receiver, message.as_string()) smtp.quit() ``` 完整代码示例: ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication sender = '发件人邮箱地址' receiver = '收件人邮箱地址' subject = '邮件主题' body = '邮件正文' message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject text = MIMEText(body) message.attach(text) with open('附件文件路径', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='pdf') attachment.add_header('Content-Disposition', 'attachment', filename='附件文件名.pdf') message.attach(attachment) smtp_server = 'SMTP服务器地址' smtp_port = 25 # SMTP服务器端口号 smtp_user = 'SMTP服务器用户名' smtp_password = 'SMTP服务器密码' smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.login(smtp_user, smtp_password) smtp.sendmail(sender, receiver, message.as_string()) smtp.quit() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值