1. 程式人生 > 程式設計 >python使用smtplib模組傳送郵件

python使用smtplib模組傳送郵件

使用smtplib模組傳送郵件,供大家參考,具體內容如下

1)使用smtplib模組傳送簡單郵件

步驟:

1.連線SMTP伺服器,並使用使用者名稱、密碼登陸伺服器
2.建立EmailMessage物件,該物件代表了郵件本身
3.呼叫sendmail()方法傳送郵件

示例:

  • 我用自己的QQ郵箱(英文地址)給自己(原始地址)發一封郵件(QQ郵箱需要授權碼(詳見))
  • smtplib.SMTP() 代表的普通SMTP連線(預設埠21)
  • smtplib.SMTP_SSL() 代表基於SSL的SMTP連線(預設埠456,安全)
import smtplib
import email.message

fromaddr = '[email protected]' # 賬號
password = '****************'  # QQ授權碼

conn = smtplib.SMTP_SSL('smtp.qq.com',465) # 建立SMTP連線 
conn.login(fromaddr,password)    # 登入郵件伺服器
msg = email.message.EmailMessage()   # 建立郵件物件
msg.set_content('您好,Python郵件')   # 設定郵件內容(普通郵件)
conn.sendmail(fromaddr,['[email protected]'],msg.as_string())  # 傳送郵件

conn.quit() # 退出連線

python使用smtplib模組傳送郵件

2)傳送內容完整的郵件

  • 為郵件設定標題、發件人名字、收件人名(設定 EmailMessage 物件對應的屬性)
  • EmailMessage的set_content() 方法的第二個引數設定為 html 可將郵件內容改為 HTML 格式
import smtplib
import email.message

fromaddr = '[email protected]'
password = '****************'
 
conn = smtplib.SMTP_SSL('smtp.qq.com',465)
conn.login(fromaddr,password) 
msg = email.message.EmailMessage()
msg.set_content('<h2>HTML郵件<h2>' + '<div style="border:1px:solid red">HTML郵件內容</div>','html','UTF-8')
msg['subject'] = 'HTML郵件'
msg['from'] = '痴迷<%s>' % fromaddr
msg['to'] = '淡然<%s>' % '[email protected]'
conn.sendmail(fromaddr,msg.as_string())

conn.quit()

python使用smtplib模組傳送郵件

3)傳送圖文並茂的郵件

在郵件中插入圖片,需要先呼叫 EmailMessage 的 add_attachment() 方法來新增附件,該方法引數:

  • maintype:指定附件的主要型別
  • subtype:指定附件的子型別
  • filename:指定該附件的檔名
  • cid=img:指定該附件的資源 ID

通過<img…/>元素來插入附件中的圖片(引用附件的cid屬性)

import smtplib
import email.message
import email.utils

fromaddr = '[email protected]'
password = '****************'
toaddr = '[email protected]'
 
conn = smtplib.SMTP_SSL('smtp.qq.com',password) 
msg = email.message.EmailMessage()
first_id = email.utils.make_msgid()
msg.set_content('<h2>HTML郵件<h2>' 
    + '<div style="border:1px:solid red">html郵件內容</div>' 
    + '<img src="cid:' + first_id[1:-1] + '">','UTF-8')
msg['subject'] = 'HTML郵件'
msg['from'] = 'wk<%s>' % fromaddr
msg['to'] = 'k<%s>' % toaddr

# 新增附件
with open('圖1.jpg','rb') as f:
 # 附件指定cid後,郵件正文可通過該cid來引用該圖片
 msg.add_attachment(f.read(),maintype='image',subtype='jepg',filename='test1.jpg',cid=first_id)

with open('圖2.jpg','rb') as f:
 msg.add_attachment(f.read(),filename='test2.jpg')
# with open('圖3.gif','rb') as f:
#  msg.add_attachement(f.read(),subtype='gif',filename='test.jpg')

conn.sendmail(fromaddr,[toaddr],msg.as_string())

conn.quit()

python使用smtplib模組傳送郵件

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。