使用Python的stmplib
和email
發(fā)送郵件:
一原茅、純文本郵件
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
#=========================================
#格式化email的頭部信息澈蟆,不然會出錯翔忽,當(dāng)做垃圾郵件
#=========================================
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = "your email"
password = "密碼或者授權(quán)碼"
to_addr = "target email"
smtp_server = "smtp.163.com"
#======================================
#注意添加Subject、To和From三個字段
#======================================
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = _format_addr('Tracy的Python <%s>' % from_addr)
msg['To'] = _format_addr('You <%s>' % to_addr)
msg['Subject'] = Header('來自SMTP……', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
#打印與服務(wù)器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
二铃彰、HTML郵件
只需要在構(gòu)造MIMEText
時绍豁,傳入HTML字符串,并且將第二個參數(shù)設(shè)置為html
即可牙捉。
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
#=========================================
#格式化email的頭部信息竹揍,不然會出錯敬飒,當(dāng)做垃圾郵件
#=========================================
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = "your email"
password = "密碼或者授權(quán)碼"
to_addr = "target email"
smtp_server = "smtp.163.com"
#==========================================================
#注意添加Subject、To和From三個字段鬼佣,更換字符串驶拱,改變第二個參數(shù)即可
#==========================================================
msg = MIMEText("<html><body><h1>Hello</h1>"+
"<p>send by <a +
"</body></html>", 'html', 'utf-8')
msg['From'] = _format_addr('Tracy的Python <%s>' % from_addr)
msg['To'] = _format_addr('You <%s>' % to_addr)
msg['Subject'] = Header('來自SMTP……', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
#打印與服務(wù)器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
三、發(fā)送帶附件的郵件
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
import smtplib
#=========================================
#格式化email的頭部信息晶衷,不然會出錯蓝纲,當(dāng)做垃圾郵件
#=========================================
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = "your email"
password = "密碼或者授權(quán)碼"
to_addr = "target email"
smtp_server = "smtp.163.com"
#======================================================
#帶附件的郵件可以看做包含若干部分的郵件:文本和各個附件本身,
#所以晌纫,可以構(gòu)造一個MIMEMultipart對象代表郵件本身税迷,
#然后往里面加上一個MIMEText作為郵件正文,
#再繼續(xù)往里面加上表示附件的MIMEBase對象即可锹漱。
#=====================================================
# 郵件對象:
msg = MIMEMultipart()
msg['From'] = _format_addr('Python愛好者 <%s>' % from_addr)
msg['To'] = _format_addr('管理員 <%s>' % to_addr)
msg['Subject'] = Header('來自SMTP的問候……', 'utf-8').encode()
# 郵件正文是MIMEText:
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# 添加附件就是加上一個MIMEBase箭养,從本地讀取一個圖片:
with open('/Users/michael/Downloads/test.png', 'rb') as f:
# 設(shè)置附件的MIME和文件名,這里是png類型:
mime = MIMEBase('image', 'png', filename='test.png')
# 加上必要的頭信息:
mime.add_header('Content-Disposition', 'attachment', filename='test.png')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的內(nèi)容讀進(jìn)來:
mime.set_payload(f.read())
# 用Base64編碼:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
server = smtplib.SMTP(smtp_server, 25)
#打印與服務(wù)器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
4哥牍、搬運(yùn)
#=========================================================================
# 加密SMTP
#
# 使用標(biāo)準(zhǔn)的25端口連接SMTP服務(wù)器時毕泌,使用的是明文傳輸,發(fā)送郵件的整個過程可能會被竊聽嗅辣。
#要更安全地發(fā)送郵件撼泛,可以加密SMTP會話,實(shí)際上就是先創(chuàng)建SSL安全連接澡谭,
#然后再使用SMTP協(xié)議發(fā)送郵件愿题。網(wǎng)易163的STMP服務(wù)SSL端口號為465/994
#=========================================================================
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr, formatdate
import smtplib
# return Alias_name <xxxx@example.com>
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
# 接收參數(shù): 發(fā)件人地址
from_addr = ''
# 接收參數(shù): 客戶端授權(quán)密碼
passwd = ''
# 接收參數(shù): 收件人地址,可多個
to_addrs = ["abc@qq.com"]
# 接收參數(shù): SMTP服務(wù)器(注意:是發(fā)件人的smtp服務(wù)器)
smtp_server = 'smtp.163.com'
# 接收參數(shù): 郵件主題
subject = '人生苦短'
# 接收參數(shù): 郵件正文
plain = '我用python!'
# 帶附件郵件
# 指定subtype為alternative,同時支持html和plain格式
msg = MIMEMultipart('alternative')
# 郵件正文中顯示圖片蛙奖,同時附件的圖片將不再顯示
# plain = 'Hello world and hello me!'
msg.attach(MIMEText(str(plain), 'plain', 'utf-8')) # 純文本
# html = '<html><body><h1>Hello</h1><p>![](cid:0)</p></body></html>'
# msg.attach(MIMEText(html, 'html', 'utf-8')) # HTML
# 添加附件:即關(guān)聯(lián)一個MIMEBase潘酗,圖片為本地讀取
with open('/home/kyxy/Desktop/dota.png', 'rb') as f:
# 設(shè)置附件中的MIME和文件名
mime = MIMEBase('image', 'jpeg', filename='dota.png')
# 加上必要的頭信息
mime.add_header('Content-Disposition', 'attachment',
filename='dota.png')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的內(nèi)容讀進(jìn)來
mime.set_payload(f.read())
# 用Base64編碼
encoders.encode_base64(mime)
# 添加到MIMEMultipart
msg.attach(mime)
# 未指定用戶別名,則客戶端會自動提取郵件地址中的名稱作為郵件的用戶別名
msg['From'] = _format_addr(from_addr)
# msg['To'] = _format_addr(to_addrs)
msg['To'] = '%s' % ','.join([_format_addr('<%s>' % to_addr)
for to_addr in to_addrs])
msg['Subject'] = Header(str(subject), 'utf-8').encode()
msg['Date'] = formatdate()
#=========================================================================
# 發(fā)送郵件
#=========================================================================
try:
# SMTP服務(wù)器設(shè)置(地址,端口):
server = smtplib.SMTP_SSL(smtp_server, 465)
# server.set_debuglevel(1)
# 連接SMTP服務(wù)器(發(fā)件人地址, 客戶端授權(quán)密碼)
server.login(from_addr, passwd)
# 發(fā)送郵件
server.sendmail(from_addr, to_addrs, msg.as_string())
print('郵件發(fā)送成功')
except smtplib.SMTPException as e:
print(e)
print('郵件發(fā)送失敗')
finally:
# 退出SMTP服務(wù)器
server.quit()