Python發送郵件(帶附件)

來源:互聯網
上載者:User

標籤:send   .com   str   python   multi   ***   use   連接埠號碼   art   

import smtplib                           #發送郵件模組

from email.mime.text import MIMEText    #定義郵件內容

from email.mime.multipart import MIMEMultipart  #用於傳送附件

 

#發送郵箱伺服器

smtpserver=‘smtp.163.com‘

 

#發送信箱使用者名密碼

user=‘[email protected]‘

password=‘*******‘

 

#發送和接收郵箱

sender=user

receives=[‘[email protected]‘,‘[email protected]‘]

 

 

#發送郵件主題和內容

subject=‘python帶附件郵件發送‘

content=‘<html><h1 style="color:red">python帶附件郵件發送測試</h1></html>‘

 

 

#構造附件內容,添加E:\Python_script\logo.png為附件

send_file=open(r"E:\Python_script\logo.png",‘rb‘).read()

 

att=MIMEText(send_file,‘base64‘,‘utf-8‘)

att["Content-Type"]=‘application/octet-stream‘

# filename為附件所顯示的名稱

att["Content-Disposition"]=‘attachment;filename="logo.png"‘

 

#構建發送與接收資訊

msgRoot=MIMEMultipart()

#添加常值內容

msgRoot.attach(MIMEText(content, ‘html‘, ‘utf-8‘))

msgRoot[‘subject‘]=subject

msgRoot[‘From‘]=sender

#添加收件者,這裡是發送給多人

msgRoot[‘To‘] = ‘,‘.join(receives)

# 添加附件

msgRoot.attach(att)

#SSL協議連接埠號碼要使用465

smtp = smtplib.SMTP_SSL(smtpserver, 465)

#HELO 向伺服器標識使用者身份

smtp.helo(smtpserver)

#伺服器返回結果確認

smtp.ehlo(smtpserver)

#登入郵箱伺服器使用者名稱和密碼

smtp.login(user,password)

print("Start send email...")

smtp.sendmail(sender,receives,msgRoot.as_string())

smtp.quit()

print("Send End!")

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.