Python發送Email

來源:互聯網
上載者:User

Python對於Email的分成兩個部分:

  1. 對於POP、SMTP的支援。
  2. 對於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()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.