Python使用SMTP發送郵件(純文本)

首先,要實現發郵件總共需要用到email模塊和smtplib模塊,其中email模塊用於構造郵件,smtplib模塊用於發送郵件,那麼先引入模塊
from email.mime.text import MIMEText
from email.header import Header
import smtplib

其中MIMEText用於構造郵件內容
構造郵件信息
message ='''
hello,world!
來自我的電腦
'''
然後用MIMEText構造最終要發送的信息
msg = MIMEText(message,'plain','utf-8')

plain表示純文本文件,還有html等,在這裏不作討論。utf-8爲了保證兼容性
這個msg還需要有‘Subject’、'From'、'To'三個鍵值對,其中'Subject'對應的是郵件的標題,'From'是發件人,'To'是收件人
msg['Subject'] = Header("來自Python的郵件",'utf-8')
msg['From'] = Header('[email protected]') #發件郵箱
msg['To'] = Header('receiver','utf-8') #收件郵箱
這樣我們的郵件信息就完成了

收發件信息
from_addr = '[email protected]' #發件郵箱
password = 'password' #郵箱密碼
to_addr = '[email protected]' #收件郵箱
smtp_server = 'smtp.qq.com' #SMTP服務器,以QQ爲例

發送
try:
server = smtplib.SMTP(smtp_server,25) #第二個參數爲默認端口爲25,有些郵件有特殊端口
print('開始登錄')
server.login(from_addr,password) #登錄郵箱
print('登錄成功')
print("郵件開始發送")
server.sendmail(from_addr,to_addr,msg.as_string()) #將msg轉化成string發出
server.quit()
print("郵件發送成功")
except smtplib.SMTPException as e:
print("郵件發送失敗",e)

完成


#!/usr/bin/python

-- coding:utf-8 --

import smtplib
from email.mime.text import MIMEText
from email.header import Header
message ='''
hello,world!
來自我的電腦
'''
msg = MIMEText(message,'plain','utf-8')

msg['From'] = Header('[email protected]')
msg['To'] = Header('[email protected]','utf-8')
msg['Subject'] = Header("來自Python的郵件",'utf-8')

from_addr = '[email protected]' #發件郵箱
password = 'qgfeddbdgfhbttjjjjcaji' #郵箱密碼
to_addr = '[email protected]' #收件郵箱
smtp_server = 'smtp.qq.com' #SMTP服務器,以新浪爲例
try:
server = smtplib.SMTP(smtp_server,25) #第二個參數爲默認端口爲25,有些郵件有特殊端口
server.login(from_addr,password) #登錄郵箱
server.sendmail(from_addr,to_addr,msg.as_string()) #將msg轉化成string發出
server.quit()
print("郵件發送成功")
except smtplib.SMTPException as e:
print("郵件發送失敗",e)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章