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


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