[Python] SMTP发送邮件
这里PYTHON脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱.
QQ邮箱利用的是加密STMP, 需要加密版本的童鞋请关注随后的更新.
TIPS: 我的本地环境是MAC系统, Windows环境需要修改相应的字符编码.
#!/usr/bin/env python # -*- coding: utf-8 -*- import smtplib import email.encoders from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase import getpass # Build a new attach instance msg = MIMEMultipart() # Mail configuration Mail_subject = 'Python test mail' Mail_content = 'Send with attachments' Recipient_list = ['XXX@126.com', 'XXX@qq.com'] SMTP_server = "smtp.126.com" Username = raw_input('Please input your Username:') Password = getpass.getpass("Please input your Password: ") mail_postfix = "126.com" # Mail attachment def attach(file_path, file_name, type, postfix): with open(file_path + "/" + file_name, 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase(type, postfix, filename = file_name) # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename = file_name) mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: email.encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime) def send_mail(recipient, title, content): # Mail info author = "%s<%s@%s>" %(Username, Username, mail_postfix) msg['Subject'] = title msg['From'] = author msg['To'] = ";".join(recipient) # send attachment msg.attach(MIMEText(content, 'plain', 'utf-8')) attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png') attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py') attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip') try: server = smtplib.SMTP() server.set_debuglevel(1) server.connect(SMTP_server) server.login(Username, Password) server.sendmail(author, recipient, msg.as_string()) server.quit() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(Recipient_list, Mail_subject, Mail_content): print "Sent Successfully" else: print "Sent Failure"
本文链接:http://www.showerlee.com/archives/1454
继续浏览:PYTHON
还没有评论,快来抢沙发!