Python自动发送邮件-smtplib和email库
一、先导入smtplib模块 导入MIMEText库用来做纯文本的邮件模板
二、发邮件几个相关的参数,每个邮箱的发件服务器不一样,以163为例子百度搜索服务器是 smtp.163.com
三、写邮件主题和正文,这里的正文是HTML格式的
四、最后调用SMTP发件服务
126mail -> qqmail send email
import uuid
import smtplib
from email.mime.text import MIMEText
#发邮件相关参数
smtpsever = 'smtp.126.com'
sender = '123@126.com'
psw = "XXX" #126邮箱授权码
receiver = '456@qq.com'
#编辑邮件的内容
# subject=u"NBA"
body=str(uuid.uuid4())
msg=MIMEText(body,'html','utf-8')
msg['from']='123@126.com'
msg['to']='456@qq.com'
# msg['subject']=subject
try:
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,uuid
from email.mime.text import MIMEText
#发邮件相关参数
smtpsever='smtp.qq.com'
sender='123@qq.com'
psw="XXXXX" #qq邮箱授权码
receiver='456@qq.com'
port=465
#编辑邮件内容
subject = u"你猜这是啥?"
body = str(uuid.uuid4())
msg=MIMEText(body,'html','utf-8')
msg['from']='123@qq.com'
msg['to']='456@qq.com'
msg['subject'] = subject
#链接服务器发送
smtp = smtplib.SMTP_SSL(smtpsever,port)
smtp.login(sender,psw) #登录
smtp.sendmail(sender,receiver,msg.as_string()) #发送
smtp.quit() #关闭
发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#发邮件相关参数
smtpsever='smtp.qq.com'
sender='123@qq.com'
#psw="xxxx" #126邮箱授权码
psw="xxxx"
receiver='456789@qq.com'
port=465
filepath="E:\\result.html" #编辑邮件的内容
with open(filepath,'rb') as fp: #读文件
mail_body=fp.read()
#主题
msg=MIMEMultipart()
msg["from"]=sender
msg["to"]=receiver
msg["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()