VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Python(email 邮件收发)

1、发送 html 文本内容的邮件

复制代码
# smtplib 负责发送邮件
import smtplib
# MIMEText 负责构造邮件内容
from email.mime.text import MIMEText
# Header 是用来构建邮件头的
from email.header import Header

smtpServer= "smtp.163.com"
sender = "zhengying0813@163.com"
passWord = "MDZWNINBZEDKXXX"
receiver = "zhengying0813@163.com"
subject = "Python email test"
# 三个参数:第一个为文本内容,第二个 html 设置文本格式,第三个 utf-8 设置编码
msg = MIMEText("<html><h1>你好!</h1></html>","html","utf-8")
# 定义邮件主题
msg["Subject"] = Header(subject,"utf-8")
msg["From"] = Header(sender,"utf-8")
msg["To"] = Header(receiver)

smtp = smtplib.SMTP()
smtp.connect(smtpServer)
# 登录 SMTP 服务器
smtp.login(sender,passWord)
# msg.as_string() 把 MIMEText 变成 str 对象
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
复制代码

 2、发送带附件的邮件

复制代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

smtpServer= "smtp.163.com"
sender = "zhengying0813@163.com"
passWord = "MDZWNINBZEDKCXXX"
receiver = "zhengying0813@163.com"
subject = "Python email test"

# 创建一个带附件的实例
msg = MIMEMultipart()
msg["Subject"] = Header(subject,"utf-8")
msg["From"] = Header(sender,"utf-8")
msg["To"] = Header(receiver)

# log.txt 为报告文件
file = open("log.txt","rb").read()
att = MIMEText(file,"base64","utf-8")
# 这里的 filename 定义邮件中显示什么名字
att["Content-Disposition"] = 'attachment; filename="log.txt"'
# 添加文件到邮件附件中去
msg.attach(att)

smtp = smtplib.SMTP()
smtp.connect(smtpServer)
smtp.login(sender,passWord)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
复制代码

 

作者:多测师特聘讲师_郑sir
出处:https://www.cnblogs.com/ZhengYing0813/
备注:本文版权归作者所有,欢迎转载和添加作者微信探讨技术,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。


相关教程