首页 > 代码库 > python之用smtplib模块使用第三方smtp发送邮件(我改写成了类,方便点)
python之用smtplib模块使用第三方smtp发送邮件(我改写成了类,方便点)
#_*_ coding:utf-8 _*_ import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Sendmail: local_hostname = [‘toby-ThinkPad-T430shhhh‘] msg = MIMEMultipart(‘related‘) def __init__(self,smtp_server,mail_user,mail_pass): self.smtp_server = smtp_server self.mail_user = mail_user self.mail_pass = mail_pass def mess(self,theme,message): Sendmail.msg[‘Subject‘] = theme # 邮件主题 html_msg = ‘‘‘ <html><head><body> <p>%s</p> </body></head></html> ‘‘‘ % message html = MIMEText(html_msg, ‘html‘, ‘utf-8‘) Sendmail.msg.attach(html) def files(self,path,filenames): files = path + filenames att = MIMEText(open(files, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) att["Content-Type"] = ‘application/octet-stream‘ att["Content-Disposition"] = ‘attachment; filename=%s‘ % filenames Sendmail.msg.attach(att) def send(self,receiver): smtp = smtplib.SMTP() smtp.connect(self.smtp_server) smtp.ehlo(self.local_hostname) # 使用ehlo指令向smtp服务器确认身份 smtp.starttls() # smtp连接传输加密 smtp.login(self.mail_user, self.mail_pass) smtp.sendmail(self.mail_user, receiver, Sendmail.msg.as_string()) smtp.quit() if __name__ == "__main__": a = Sendmail(‘xxxx.xxxx.com‘,‘xxxxx@xxxx.com‘,‘xxxxxx‘) #实例化一个发送邮件的对象 a.mess(‘hello world‘,‘this is test mail‘) #定义主题,消息 a.files(‘/var/log/‘,‘syslog.2.gz‘) #这是发送邮件 定义路径、文件名 a.send(‘xxxx@qq.com‘) #收件人
本文出自 “FA&IT运维-Q群:223843163” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1875021
python之用smtplib模块使用第三方smtp发送邮件(我改写成了类,方便点)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。