记录一下自己的第一个成功的python实例,使用python代理发送邮件。
其中有三种方法,前两种是普通的文本文件发送邮件,第三种是以附件的形式发送邮件!
以下是具体的python内容:
#!/usr/bin/python #-*- coding: utf-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header sender = ‘wangyi@126.com‘ to1 = ‘tenxun@qq.com‘ to = ["tenxun@qq.com", "123456@qq.com"] # 多个收件人的写法 subject = ‘From Python Email test‘ smtpserver = ‘smtp.126.com‘ username = ‘wangyi‘ password = ‘123456‘ mail_postfix = ‘126.com‘ contents = ‘这是一个Python的测试邮件,收到请勿回复,谢谢!!‘ attachment_1 = ‘/tmp/test.txt‘ # 第一种方法-普通文本形式的邮件 def send_mail(to_list, sub, content): me = "Hello"+"" msg = MIMEText(content, _subtype=‘plain‘, _charset=‘utf-8‘) msg[‘Subject‘] = subject msg[‘From‘] = me msg[‘To‘] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(smtpserver) server.login(username, password) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == ‘__main__‘: if send_mail(to, subject, contents): print "邮件发送成功! " else: print "失败!!!" # 第二种方法-普通文本形式的邮件 # msg = MIMEText(‘邮件内容‘,‘_subtype文件格式‘,‘字符集‘) 中文需参数‘utf-8’,单字节字符不需要 msg = MIMEText(contents, _subtype=‘plain‘, _charset=‘utf-8‘) msg[‘Subject‘] = subject msg[‘From‘] = sender msg[‘To‘] = to1 try: smtp = smtplib.SMTP() smtp.connect(smtpserver, 25) smtp.login(username, password) smtp.sendmail(sender, to1, msg.as_string()) smtp.quit() print "发送成功!" except: print "失败" # 第三种方法-发送附件 # 创建一个带附件的实例 msg = MIMEMultipart() # 构造附件1 att1 = MIMEText(open(attachment_1, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) att1["Content-Type"] = ‘application/octet-stream‘ att1["content-Disposition"] = ‘attachment; filename="test.txt"‘ #这里的filename是附件的名字可以自定义 msg.attach(att1) # 加邮件头 msg[‘From‘] = sender msg[‘To‘] = to1 msg[‘Subject‘] = subject # 发送邮件 try: server = smtplib.SMTP() server.connect(smtpserver) server.login(username, password) server.sendmail(sender, to1, msg.as_string()) server.quit() print "发送成功" except: print "失败"
本文出自 “行 者--->” 博客,请务必保留此出处http://liumissyou.blog.51cto.com/4828343/1728392
原文地址:http://liumissyou.blog.51cto.com/4828343/1728392