Python发送邮件

  记录一下成功的python发送邮件的实例,使用python代理发送邮件。
其中有三种方法,前两种是普通的文本文件发送邮件,第三种是以附件的形式发送邮件!
以下是具体的python内容:

#!/usr/bin/python
#-*- coding: utf-8 -*-
# file_name: mail_send.py

import smtplib    
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart
from email.header import Header    
sender = '[email protected]'    
to1 = '[email protected]'
to = ["[email protected]", "[email protected]"]  # 多个收件人的写法
subject = 'From Python Email test'    
smtpserver = 'smtp.126.com'    
username = 'wangyi'    
password = '123456'    
mail_postfix = '126.com'
contents = '这是一个Python的测试邮件,收到请勿回复,谢谢!!'
p_w_upload_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(p_w_upload_1, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["content-Disposition"] = 'p_w_upload; 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 "失败"

运行

prython mail_send.py


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章