自动化之使用python3发送邮件
2018-09-26 本文已影响9人
test小星星
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
class SendMail():
'''
发送邮件
'''
def __init__(self,smtpserver, username, password, sender, receiver):
self.smtpserver = smtpserver #发送邮箱服务器
self.username = username #发送邮箱用户
self.password = password #密码
self.sender = sender #发送邮箱
self.receiver = receiver #接收邮箱
self.msg = MIMEMultipart('alternative')
def send_text(self, title, text, annex_file):
#标题信息
self.msg['Subject'] = Header(title,'utf-8')
#正文内容
part1 = MIMEText(text,'plain','utf-8')
self.msg.attach(part1)
# 构造附件
with open(annex_file,'rb') as f:
send_body = f.read()
att = MIMEText(send_body,'base64','utf-8')
att["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att["Content-Disposition"] = 'attachment;filename="result.html"'
self.msg.attach(att)
self.msg['From'] = self.sender
self.msg['To'] = self.receiver #"my fans" #接收器的名字可以定制
#连接发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(self.smtpserver,25) # 25 为 SMTP 端口号
smtp.login(self.username,self.password)
smtp.sendmail(self.sender,self.receiver,self.msg.as_string())
smtp.quit()
print("发送成功")
except smtplib.SMTPException as e:
print ("Error: cannot send my email")
print (e)