Skip to content

Commit

Permalink
修复 Python3.9 邮件错误
Browse files Browse the repository at this point in the history
  • Loading branch information
0xJacky committed Aug 27, 2021
1 parent 9ec65b6 commit aebc17d
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,34 @@
from email.mime.application import MIMEApplication
from email.header import Header


class Mail:
def __init__(self):
# 构建alternative结构
self.msg = MIMEMultipart('alternative')
self.msg = MIMEMultipart('alternative')
self.msg['From'] = '%s <%s>' % (Header(settings.From).encode(), settings.UserName)
self.msg['To'] = settings.To
self.msg['To'] = str(settings.To)
self.msg['message_id'] = email.utils.make_msgid()
self.msg['Date'] = email.utils.formatdate()

def send(self, subject, content):
self.msg['Subject'] = subject
# 构建alternative的text/plain部分
textplain = MIMEText(content, _subtype='plain', _charset='UTF-8')
self.msg.attach(textplain)
# 发送邮件
try:
client = smtplib.SMTP_SSL()
#SMTP普通端口为25或80
if settings.Port == 80:
client = smtplib.SMTP()
else:
client = smtplib.SMTP_SSL(settings.Host)
# SMTP普通端口为25或80
client.connect(settings.Host, settings.Port)
#开启DEBUG模式
# 开启DEBUG模式
client.set_debuglevel(0)
client.login(settings.UserName, settings.PassWord)
#发件人和认证地址必须一致
#备注:若想取到DATA命令返回值,可参考 smtplib 的 sendmaili 封装方法:
# 发件人和认证地址必须一致
# 备注:若想取到DATA命令返回值,可参考 smtplib 的 sendmaili 封装方法:
# 使用SMTP.mail/SMTP.rcpt/SMTP.data方法
client.sendmail(settings.UserName, settings.To, self.msg.as_string())
client.quit()
Expand All @@ -44,10 +49,10 @@ def send(self, subject, content):
except smtplib.SMTPSenderRefused as e:
print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
print ('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
print ('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
print ('邮件发送失败, ', e.message)
print('邮件发送失败, ', e.message)
except Exception as e:
print ('邮件发送异常, ', str(e))
print('邮件发送异常, ', str(e))

0 comments on commit aebc17d

Please sign in to comment.