Python對於Email的分成兩個部分:
- 對於POP、SMTP的支援。
- 對於Email資料的支援。
第一部分: 用POP、SMTP來讀取信件:
import getpass, poplibM = poplib.POP3('localhost')M.user(getpass.getuser())M.pass_(getpass.getpass())numMessages = len(M.list()[1])for i in range(numMessages): for j in M.retr(i+1)[1]:
第二部分: 資料的支援:
- 發送普通文本類型郵件:
# Import smtplib for the actual sending functionimport smtplib# Import the email modules we'll needfrom email.mime.text import MIMEText# Open a plain text file for reading. For this example, assume that# the text file contains only ASCII characters.fp = open(textfile, 'rb')# Create a text/plain messagemsg = MIMEText(fp.read())fp.close()# me == the sender's email address# you == the recipient's email addressmsg['Subject'] = 'The contents of %s' % textfilemsg['From'] = memsg['To'] = you# Send the message via our own SMTP server, but don't include the# envelope header.s = smtplib.SMTP()s.connect()s.sendmail(me, [you], msg.as_string())s.close()
- 發送帶有圖片附件的郵件:
import smtplib
# 需要匯入的Module
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
# 產生需要的Object
email message.msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me ==源地址
# family = 需要發送的地址
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'
#pngfiles是一些圖形的檔案名稱列表
for file in pngfiles:
# 開啟檔案
# 自動探測圖形類型
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# 通過SMTP發送
s = smtplib.SMTP()
s.connect()
s.sendmail(me, family, msg.as_string())
s.close()