1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Python自动发送邮件-smtplib和email库

Python自动发送邮件-smtplib和email库

时间:2020-05-31 03:30:53

相关推荐

Python自动发送邮件-smtplib和email库

一、先导入smtplib模块 导入MIMEText库用来做纯文本的邮件模板

二、发邮件几个相关的参数,每个邮箱的发件服务器不一样,以163为例子百度搜索服务器是

三、写邮件主题和正文,这里的正文是HTML格式的

四、最后调用SMTP发件服务

126mail -> qqmail send email

import uuidimport smtplibfrom email.mime.text import MIMEText#发邮件相关参数smtpsever = ''sender = '123@'psw = "XXX" #126邮箱授权码receiver = '456@'#编辑邮件的内容# subject=u"NBA"body=str(uuid.uuid4())msg=MIMEText(body,'html','utf-8')msg['from']='123@'msg['to']='456@'# msg['subject']=subjecttry:smtp = smtplib.SMTP()smtp.connect(smtpsever)smtp.login(sender,psw)smtp.sendmail(sender,receiver,msg.as_string())print ("邮件发送成功")except smtplib.SMTPException:print ("Error: 无法发送邮件")

qqmail->126mail send email

'''遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!'''import smtplib,uuidfrom email.mime.text import MIMEText#发邮件相关参数smtpsever=''sender='123@'psw="XXXXX" #qq邮箱授权码receiver='456@'port=465#编辑邮件内容subject = u"你猜这是啥?"body = str(uuid.uuid4())msg=MIMEText(body,'html','utf-8')msg['from']='123@'msg['to']='456@'msg['subject'] = subject#链接服务器发送smtp = smtplib.SMTP_SSL(smtpsever,port)smtp.login(sender,psw)#登录smtp.sendmail(sender,receiver,msg.as_string()) #发送smtp.quit() #关闭

发送带附件的邮件

import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart#发邮件相关参数smtpsever=''sender='123@'#psw="xxxx" #126邮箱授权码psw="xxxx"receiver='456789@'port=465filepath="E:\\result.html" #编辑邮件的内容with open(filepath,'rb') as fp: #读文件mail_body=fp.read()#主题msg=MIMEMultipart()msg["from"]=sendermsg["to"]=receivermsg["subject"]=u"这个我的主题"#正文body=MIMEText(mail_body,"html","utf-8")msg.attach(body)att = MIMEText(mail_body,"base64","utf-8")att["Content-Type"] = "application/octet-stream"att["Content-Disposition"] = 'attachment; filename="test_report.html"'msg.attach(att)try:smtp=smtplib.SMTP()smtp.connect(smtpsever) #连接服务器smtp.login(sender,psw)except:smtp=smtplib.SMTP_SSL(smtpsever,port)smtp.login(sender,psw) #登录smtp.sendmail(sender,receiver,msg.as_string()) #发送smtp.quit()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。