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
代码完整链接:传送门