python發送郵件
代碼完整鏈接:傳送門
使用SMTP
- 需要配合各郵件服務器,如163的SMTP,騰訊的,至於如何開啓,自行百度。
導入模塊
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
登錄
try:
self.smtpObj = smtplib.SMTP_SSL(usr_server, 465)
self.smtpObj.login(usr_name, usr_pwd)
self.__login_fail = True
except smtplib.SMTPException as e:
self.__login_fail = False
print("login fail:" + str(e))
usr_server
取各服務器的地址,如163.stmp.com
usr_name
取你的郵箱地址usr_pwd
取你的郵箱授權碼
配置郵件
self.msg = MIMEMultipart() #多元,可用attach
def setSender(self, sdr_address):
self.msg["From"] = "{}".format(sdr_address)
def setReciever(self, rcr_address):
self.msg["To"] = ",".join(rcr_address)
self.reciever_list = rcr_address
def setSubject(self, title):
self.msg["Subject"] = title
添加純文本內容
def addPlainContent(self, p_ct):
self.msg.attach(MIMEText(p_ct, "plain", "utf-8"))
添加html內容
def addHtmlContent(self, html):
self.msg.attach(MIMEText(html, "html", "utf-8"))
添加附件
def addAttachFile(self, file_address):
try:
file_stream = open(file_address, "rb").read()
except:
print("load file fail.")
ath = MIMEApplication(file_stream)
file_name = file_address.split("\\")
ath.add_header('Content-Disposition', 'attachment', filename=file_name[-1])
self.msg.attach(ath)
發送
def sendEmail(self):
try:
self.smtpObj.sendmail(self.usr_name, self.reciever_list, self.msg.as_string())
print("send successfully.")
return True
except smtplib.SMTPException as e:
print("send fail:" + str(e))
return False
代碼完整鏈接:傳送門