Python 3(13)使用 smtplib 模块发送 SMTP 邮件

Python3 入门专栏

http://blog.csdn.net/column/details/19679.html


Python  发送 SMTP 邮件


python 的 smtplib 模块对 smtp 协议进行了简单的封装,可以用于发送 smtp 协议的电子邮件;

发送普通邮件

 
import smtplib
from email.header import Header
from email.mime.text import MIMEText
# 使用 163 邮箱的 SMTP 服务
mail_host = "smtp.163.com"              # smtp 服务器
mail_user = "helloworld_assad@163.com"  # smtp 服务器验证用户名
mail_password = "*************"         # smtp 服务器验证密码(smtp 授权码)
sender = "helloworld_assad@163.com"          # 发送地址
receivers = ["yulinying_1994@outlook.com"]   # 接收地址
# 信息对象(dict 对象)
message = MIMEText("Hello world", "plain", "utf-8")
message["From"] = Header("assad", "utf-8")
message["To"] = Header("Mr.lin", "utf-8")
message["Subject"] = Header("python smtp 邮件测试", "utf-8")
try:
    server = smtplib.SMTP()                  # 创建 SMTP 对象
    server.connect(mail_host, 25)            # 连接 smtp 服务器,默认端口25
    server.login(mail_user, mail_password)   # 登陆 smtp 服务器
    server.sendmail(sender, receivers, message.as_string())   # 发送邮件
    print("send email success")
except smtplib.SMTPException as err:
    print("send email fail")
    print("Error message:", err)

发送 HTML 文本邮件

 
import smtplib
from email.header import Header
from email.mime.text import MIMEText
# 使用 163 邮箱的 SMTP 服务
mail_host = "smtp.163.com"              # smtp 服务器
mail_user = "helloworld_assad@163.com"  # smtp 服务器验证用户名
mail_password = "*************"         # smtp 服务器验证密码(smtp 授权码)
sender = "helloworld_assad@163.com"          # 发送地址
receiver = "yulinying_1994@outlook.com"   # 接收地址
mail_msg = """
<h1>Hello World!</h1>
<p>this is a test email from python smtp</p>
"""
# 信息对象(dict 对象)
message = MIMEText(mail_msg, "html", "utf-8")
message["From"] = Header(sender, "utf-8")
message["To"] = Header(receiver, "utf-8")
message["Subject"] = Header("python smtp html 邮件测试", "utf-8")
try:
    server = smtplib.SMTP()                  # 创建 SMTP 对象
    server.connect(mail_host, 25)            # 连接 smtp 服务器,默认端口25
    server.login(mail_user, mail_password)   # 登陆 smtp 服务器
    server.sendmail(sender, receiver, message.as_string())   # 发送邮件
    print("send email success")
except smtplib.SMTPException as err:
    print("send email fail")
    print("Error message:", err)

发送带有附件的邮件

 
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 使用 163 邮箱的 SMTP 服务
mail_host = "smtp.163.com"              
mail_user = "helloworld_assad@163.com" 
mail_password = "*************"        
sender = "helloworld_assad@163.com"   
receiver = "yulinying_1994@outlook.com" 
 
# 邮件信息对象
message = MIMEMultipart()
message['From'] = Header(sender, 'utf-8')
message['To'] =  Header(receiver, 'utf-8')
message['Subject'] = Header('python smtp 邮件附件测试', 'utf-8')
 
# 邮件正文内容
message.attach(MIMEText('this is a test email from python smtp', 'plain', 'utf-8'))
 
# 附件1:当前目录下的 test1.txt 文件
att1 = MIMEText(open('test1.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="test1.txt"'
# 附件2:当前目录下的 test2.txt 文件
att2 = MIMEText(open('test2.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="test2.txt"'
# 向邮件对象添加附件对象
message.attach(att1)
message.attach(att2)
 
try:
    server = smtplib.SMTP()                 
    server.connect(mail_host, 25)            
    server.login(mail_user, mail_password)  
    server.sendmail(sender, receiver, message.as_string())   
    print("send email success")
except smtplib.SMTPException as err:
    print("send email fail")
    print("Error message:", err)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值