【Python-Mail邮件发送】不飞则已,一飞冲天;不鸣则已,一鸣惊人。这篇文章主要讲述Python-Mail邮件发送相关的知识,希望能为你提供帮助。
文章图片
导入模块
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
from email.mime.base import MIMEBase
from datetime import datetime
发送html格式的邮件读取html文件内容发送邮件,转发和抄送没做函数参数,需要_format_addr函数进行美化成html格式的内容
def Sendmail(Smtp_server,Username,Password,addrlist,Title,Text):
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr ((Header(name, \'utf-8\').encode (), addr))
msg = MIMEText(Text, \'html\', \'utf-8\')msg[\'Subject\'] = Header(Title, \'utf-8\').encode() #邮件标题
msg[\'From\'] = _format_addr(\'cola <
{}>
\'.format(Username)) # 发件人信息
# msg[\'To\'] = _format_addr ("liu <
1431075018@qq.com>
") #转发
# msg[\'CC\'] = _format_addr (
#"Hu Wei <
zhang@qq.com>
,liu <
liu@qq.com>
") #抄送
server = smtplib.SMTP(Smtp_server)
server.login(Username, Password)
server.sendmail(Username, addrlist, msg.as_string ())
server.quit()if __name__ == "__main__":
with open(\'test.html\',\'r\') as f:
Text = f.read()
Sendmail(
Smtp_server = "smtp.exmail.qq.com",
Username = "haoxincheng@qq.com",
Password = "N24BfPgPk;kUHRVy",
addrlist = [ "143107@qq.com","1850@163.com" ],
Title = "MongoDB表日期检查是否是下一个交易日",
Text = Text
)
发送附件的邮件在原有的发送html邮件基础上做的更改
def Sendmail(Smtp_server,Username,Password,addrlist,Title,Text):
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr ((Header(name, \'utf-8\').encode (), addr))
msg = MIMEMultipart() #构建一个方法,attach
msg.attach(MIMEText(Title, \'html\', \'utf-8\'))msg[\'Subject\'] = Header(Title, \'utf-8\').encode() #邮件标题
msg[\'From\'] = _format_addr(\'cola <
{}>
\'.format(Username)) # 发件人信息
# msg[\'To\'] = _format_addr ("liu <
1431075018@qq.com>
") #转发
# msg[\'CC\'] = _format_addr (
#"Hu Wei <
zhang@qq.com>
,liu <
liu@qq.com>
") #抄送with open(\'20210910.log\', \'rb\') as f:
# 设置附件的MIME和文件名,这里是png类型,mime类型可以百度
mime = MIMEBase(\'text\', \'plain\', filename=\'20210910.log\')
# 加上必要的头信息:
mime.add_header(\'Content-Disposition\', \'attachment\', filename=\'20210910.log\')
mime.add_header(\'Content-ID\', \'<
0>
\')
mime.add_header(\'X-Attachment-Id\', \'0\')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
server = smtplib.SMTP(Smtp_server)
server.login(Username, Password)
server.sendmail(Username, to_addr, msg.as_string ())
server.quit()
if __name__ == "__main__":
with open(\'test.html\',\'r\') as f:
Text = f.read()
Sendmail(
Smtp_server = "smtp.exmail.qq.com",
Username = "haoxincheng@qq.com",
Password = "N24BfPgPk。sdUHRVy",
addrlist = [ "1431075018@qq.com","18501422535@163.com" ],
Title = "邮件来了",
Text = Text
)
推荐阅读
- 带你认识网络世界,什么是网络协议分层有什么好处
- # 聊一聊悟空编辑器 #
- 解密诡异并发问题的幕后黑手(可见性问题)
- Dokcer进阶-初识DockerFile
- 拉勾java高薪训练营
- 拉勾数据分析实战训练营
- 使用 du 检查 Linux 上已用的磁盘空间
- vim编辑器的常见使用
- 运维常问的面试题目