Python中使用SMTP發送郵件的例子

來源:互聯網
上載者:User

一,SMTP發送郵件

這裡PYTHON指令碼實現的是登陸126的SMTP將郵件發送到QQ郵箱.
QQ郵箱利用的是加密STMP, 需要加密版本的童鞋請關注隨後的更新.
TIPS: 我的本地環境是MAC系統, Windows環境需要修改相應的字元編碼.

#!/usr/bin/env python# -*- coding: utf-8 -*-import smtplib  import email.encodersfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseimport getpass# Build a new attach instancemsg = MIMEMultipart()# Mail configurationMail_subject = 'Python test mail'Mail_content = 'Send with attachments'Recipient_list = ['XXX@126.com', 'XXX@qq.com']SMTP_server = "smtp.126.com"  Username = raw_input('Please input your Username:')  Password = getpass.getpass("Please input your Password: ")   mail_postfix = "126.com" # Mail attachmentdef attach(file_path, file_name, type, postfix):    with open(file_path + "/" + file_name, 'rb') as f:        # 設定附件的MIME和檔案名稱,這裡是png類型:        mime = MIMEBase(type, postfix, filename = file_name)        # 加上必要的頭資訊:        mime.add_header('Content-Disposition', 'attachment', filename = file_name)        mime.add_header('Content-ID', '<0>')        mime.add_header('X-Attachment-Id', '0')        # 把附件的內容讀進來:        mime.set_payload(f.read())        # 用Base64編碼:        email.encoders.encode_base64(mime)        # 添加到MIMEMultipart:        msg.attach(mime)  def send_mail(recipient, title, content):     # Mail info    author = "%s<%s@%s>" %(Username, Username, mail_postfix)    msg['Subject'] = title      msg['From'] = author      msg['To'] = ";".join(recipient)    # send attachment    msg.attach(MIMEText(content, 'plain', 'utf-8'))    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')    try:          server = smtplib.SMTP()        server.set_debuglevel(1)         server.connect(SMTP_server)          server.login(Username, Password)          server.sendmail(author, recipient, msg.as_string())          server.quit()          return True      except Exception, e:        print str(e)        return Falseif __name__ == '__main__':     if send_mail(Recipient_list, Mail_subject, Mail_content):         print "Sent Successfully"      else:         print "Sent Failure"

二,SMTP(SSL)發送郵件


這裡需要注意的是大家使用QQ郵箱(SMTL over SSL)時, 需要首先在其網頁用戶端後台開啟SMTP/POP服務, 並且設定QQ郵箱獨立密碼作為SMTP登陸密碼, 這樣在使用MUA時就不會報Authentication failed的錯誤.
QQ郵箱 POP3連接埠: 995 SMTP連接埠: 587
密碼使用QQ郵箱獨立密碼

#!/usr/bin/env python# -*- coding: utf-8 -*-import smtplib  import email.encodersfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseimport getpass# Build a new attach instancemsg = MIMEMultipart()# Mail configurationMail_subject = 'Python test mail'Mail_content = 'Send with pic attachment'Recipient_list = ['XXX@126.com', 'XXX@qq.com']SMTP_server = "smtp.qq.com"  SMTP_port = "587"Username = raw_input('Please input your Username:')  Password = getpass.getpass("Please input your Password: ")   mail_postfix = "qq.com" # Mail attachmentdef attach(file_path, file_name, type, postfix):    with open(file_path + "/" + file_name, 'rb') as f:        # 設定附件的MIME和檔案名稱,這裡是png類型:        mime = MIMEBase(type, postfix, filename = file_name)        # 加上必要的頭資訊:        mime.add_header('Content-Disposition', 'attachment', filename = file_name)        mime.add_header('Content-ID', '<0>')        mime.add_header('X-Attachment-Id', '0')        # 把附件的內容讀進來:        mime.set_payload(f.read())        # 用Base64編碼:        email.encoders.encode_base64(mime)        # 添加到MIMEMultipart:        msg.attach(mime)  def send_mail(recipient, title, content):     # Mail info    author = "%s<%s@%s>" %(Username, Username, mail_postfix)    msg['Subject'] = title      msg['From'] = author      msg['To'] = ";".join(recipient)    # Send attachment    msg.attach(MIMEText(content, 'plain', 'utf-8'))    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')    try:          server = smtplib.SMTP(SMTP_server, SMTP_port)        server.starttls()        server.set_debuglevel(1)           server.login(Username, Password)          server.sendmail(author, recipient, msg.as_string())          server.quit()          return True      except Exception, e:        print str(e)        return Falseif __name__ == '__main__':     if send_mail(Recipient_list, Mail_subject, Mail_content):         print "Sent Successfully"      else:         print "Sent Failure"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.