Python-Mail邮件发送
Posted 可乐运维
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
)
以上是关于Python-Mail邮件发送的主要内容,如果未能解决你的问题,请参考以下文章