python之路:發附帶檔案的郵件

來源:互聯網
上載者:User

標籤:pen   mem   佔用   imp   app   模式   cat   erro   head   

發郵件的思路(借用第三方服務):

1、類比伺服器其中有:伺服器位址,寄件者地址、寄件者的密碼

2、建立一個帶附件的執行個體:1、建立一個massage 2、massage包括髮送者的地址、接受者的地址、標題

3、對本文轉化為文字模式,MIMEText函數,它的參數有:郵件的內容或檔案(文檔、視頻、圖片這一些你都要讀取檔案才能發送)名)、郵件的格式、utf-8

4、添加本文:用attach函數,可以運用多個attach函數傳遞檔案

5、發郵件:進入服務端(登入)login(登入函數)、發送sendmail(發送),需要的參數有:發送的地址、接收者、message.as_string()

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

 

#類比伺服器
#SMTP伺服器
SMTPServer="smtp.163.com"
#發郵件的地址
Sender="xxxx@163.com"
#寄件者郵件的授權密碼
passwd="xxxxx"  

# 建立一個帶附件的執行個體
message = MIMEMultipart()
message[‘From‘] = Sender

message[‘To‘] = "xxxx@qq.com"
subject = ‘Python SMTP 郵件測試‘
message[‘Subject‘] = subject
# 郵件內文內容
message.attach(MIMEText(‘這是菜鳥教程Python 郵件發送測試……‘, ‘plain‘, ‘utf-8‘))

# 構造附件1

att1 = MIMEText(open(檔案名稱, ‘rb‘).read(), ‘base64‘, ‘utf-8‘)
att1["Content-Type"] = ‘application/octet-stream‘
# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att1["Content-Disposition"] = ‘attachment; filename="檔案名稱"‘
message.attach(att1)

# 構造附件2

att2 = MIMEText(open(檔案名稱, ‘rb‘).read(), ‘base64‘, ‘utf-8‘)
att2["Content-Type"] = ‘application/octet-stream‘
att2["Content-Disposition"] = ‘attachment; filename="檔案名稱"‘
message.attach(att2)

try:
       mailServer = smtplib.SMTP(SMTPServer, 25)  # 25為連接埠號碼(郵件),0-1024都被系統佔用了
    # 登入郵箱
    mailServer.login(Sender, passwd)  # 需要的是,郵箱的地址和授權密碼
    # 傳送檔案
    mailServer.sendmail(Sender, ["xxxx@qq.com"], message.as_string())
    print("郵件發送成功")
except smtplib.SMTPException:
    print("Error: 無法發送郵件")

 

python之路:發附帶檔案的郵件

聯繫我們

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