Python发送带附件的SMTP邮件代码
发布时间:2020-05-25 00:47:35 所属栏目:Python 来源:互联网
导读:Python发送带附件的SMTP邮件代码
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 #coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart#python2.4及之前版本该模块不是这样调用的,而是email.MIMEMultipart.MIMEMultipart(),下同
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = '[emailprotected]'#发件人地址
receiver = '[emailprotected]'#收件人地址
smtpserver = 'smtp.qq.com'#邮件服务器
username = '123456789'#用户名
password = 'abcdefg'#密码
smtp = smtplib.SMTP()
def send_email(msg,file_name):
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = file_name#邮件标题,这里我把标题设成了你所发的附件名
msgText = MIMEText('%s'%msg,'html','utf-8')#你所发的文字信息将以html形式呈现
msgRoot.attach(msgText)
att = MIMEText(open('%s'%file_name,'rb').read(),'base64','utf-8')#添加附件
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"'%file_name
msgRoot.attach(att)
while 1:#持续尝试发送,直到发送成功
try:
smtp.sendmail(sender,receiver,msgRoot.as_string())#发送邮件
break
except:
try:
smtp.connect(smtpserver)#连接至邮件服务器
smtp.login(username,password)#登录邮件服务器
except:
print "failed to login to smtp server"#登录失败
if __name__ == "__main__":
MSG=""#要发送的文字
FILE=""#要发送的文件
send_email(MSG,FILE)
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
