from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr,formataddr import smtplib def mail(subject='Ansible error mail', sender='[email protected]'(邮件服务器用户), to='root', cc=None, bcc=None, body=None): if not body: body = subject smtp = smtplib.SMTP('ip')###邮件服务器ip地址 content = 'From: %s\n' % sender content += 'To: %s\n' % to if cc: content += 'Cc: %s\n' % cc content += 'Subject: %s\n\n' % subject content += body addresses = to.split(',') if cc: addresses += cc.split(',') if bcc: addresses += bcc.split(',') for address in addresses: smtp.sendmail(sender, address, content) smtp.quit() mail_host = 'ip' mail_user = '[email protected]' mail_pwd = "########" to_maillist = ['[email protected]','[email protected]','[email protected]'] def send_mail(content,mailto,get_sub): print 'Setting MIMEText' msg = MIMEText(content.encode('utf8'),_subtype='html',_charset='utf8') msg['From'] = mail_user msg['Subject'] = '<%s>' %get_sub msg['To'] = ",".join(mailto) try: print 'connecting' ,mail_host s = smtplib.SMTP_SSL(mail_host,465) s.set_debuglevel(1) print 'login to mail_host' s.login(mail_user,mail_pwd) print 'send email' s.sendmail(mail_user,mailto,msg.as_string()) print 'close the connection between the mail server' s.quit() except Exception as e: print 'exception',e
脚本2
#!/usr/bin/env python # -*- coding: utf-8 -*- # Abstract: send mail import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication class Mail: def __init__(self, smtp, user, pwd): self.smtp = smtp self.user = user ##使用邮件服务器的用户也就是发件人的邮箱地址 self.pwd = passwd self.isauth = True def parse_send(self, subject, content, plugin): return subject, content, plugin def send(self, subject, content, tolist, cclist=[], plugins=[]): msg = MIMEMultipart() msg.set_charset('utf-8') msg['from'] = self.user msg['to'] = ','.join(tolist) if cclist: msg['cc'] = ','.join(cclist) msg['subject'] = subject msg.attach(MIMEText(content, 'html', 'utf-8')) for plugin in plugins: f = MIMEApplication(plugin['content']) f.add_header('content-disposition', 'attachment', filename=plugin['subject']) msg.attach(f) s = smtplib.SMTP(self.smtp) s.set_debuglevel(smtplib.SMTP.debuglevel) if self.isauth: s.docmd("EHLO %s" % self.smtp) try: s.starttls() except smtplib.SMTPException, e: pass # smtp 服务器不支持 ssl try: s.login(self.user, self.pwd) except smtplib.SMTPException, e: pass # smtp 服务器不需要登陆 r = s.sendmail(self.user, tolist, msg.as_string()) s.close() return r if __name__ == "__main__": subject = '发送邮件测试' content = '测试' mail = Mail('211.151.144.200', '', '') tolist = ['[email protected]','[email protected]'] mail.send(subject, content, tolist) print 'mail was sent!'