一、开通邮箱SMPT服务
以QQ邮箱为例:
1.打开邮箱 - 设置 - 账户
如果出现了如下情况,到QQ安全中心 关闭邮箱登录保护 即可
2.开启IMAP/SMTP服务
3.生成授权码(之后会当成邮箱的密码)
二:邮件发送
1.封装的邮件发送代码
import smtplib
from typing import Tuple
from email.utils import formataddr
from email.mime.text import MIMEText
class SendEmailClient:
def __init__(self):
self.sender_server = 'smtp.qq.com'
self.sender_port = 465
self.sender_nickname = 'xxx'
self.sender_account = 'XXXXXXXXX@qq.com'
self.sender_password = 'XXXXXXXX'
def send_normal_email(self, receiver_account: str, receiver_nickname: str, title: str, content: str) -> Tuple[bool, str]:
"""
发送普通邮件(只有内容,没有附件)
:param receiver_account: 收件人邮箱账户
:param receiver_nickname: 收件人昵称
:param title: 邮件标题
:param content: 邮件内容
:return: tuple(bool,发送提示)
"""
message = MIMEText(_text=content, _subtype='plain', _charset='utf-8')
message['From'] = formataddr([self.sender_nickname, self.sender_account])
message['To'] = formataddr([receiver_nickname, receiver_account])
message['Subject'] = title
result, msg = True, '邮件发送成功!'
try:
server = smtplib.SMTP_SSL(self.sender_server, self.sender_port)
server.login(self.sender_account, self.sender_password)
server.sendmail(self.sender_account, [receiver_account, ], message.as_string())
server.quit()
except Exception as e:
result = False
msg = f'邮件发送失败:{e}'
return result, msg
se_client = SendEmailClient()
se_client.send_normal_email('XXXXXXXXX@qq.com', '美女美女', '测试邮件', '我爱你')
2.发送效果
normal_email(‘XXXXXXXXX@qq.com’, ‘美女美女’, ‘测试邮件’, ‘我爱你’)
|