本文以第三方QQ邮箱服务器演示如何使用python的smtplib+email完成邮箱发送功能
开启QQ邮箱SMTP服务
开启的最后一步是发送短信验证,获取 authorization。 QQ官方获取授权码的帮助文档。
使用SMTP服务有POP和IMAP(Internet Message Access Protocol)两种协议,我们选择使用IMAP,具体差异查看QQ邮箱帮助文档。
使用IMAP服务的SSL加密方式的通用配置如下:
接收邮件服务器:imap.qq.com,使用SSL,端口号993
发送邮件服务器:smtp.qq.com,使用SSL,端口号465或587
账户名:您的QQ邮箱账户名(如果您是VIP帐号或Foxmail帐号,账户名需要填写完整的邮件地址)
密码:您的QQ邮箱authorization
电子邮件地址:您的QQ邮箱的完整邮件地址
import smtplib
from email.mime.text import MIMEText
smtpHost = "smtp.qq.com" # 邮件服务器地址
port = 465 # 邮件服务器端口
server = smtplib.SMTP_SSL(smtpHost, port)
sender = '418***167@qq.com' # 发件人邮箱账号
authorization = 'spi********idj' # QQ邮箱授权码
server.login(sender, authorization) # 括号中对应的是发件人邮箱账号、邮箱密码
mailboxContainer = MIMEText('Hello Python!', "plain", "utf-8") # 创建文本类型容器
mailboxContainer['Subject'] = "python发送的邮件" # 邮箱主题
mailboxContainer['From'] = sender # 邮箱发送人
receiver_to = ['y****@****.com']
mailboxContainer["To"] = ",".join(receiver_to) # 邮箱接收人
receiver_cc = []
mailboxContainer['Cc'] = ",".join(receiver_cc) # 邮箱抄送人
receiver = receiver_to + receiver_cc # 接收邮箱的人(包含接收和抄送)
server.sendmail(sender, receiver, mailboxContainer.as_string())
server.quit()
收件结果如下:
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtpHost = "smtp.qq.com" # 邮件服务器地址
port = 465 # 邮件服务器端口
server = smtplib.SMTP_SSL(smtpHost, port)
sender = '418XXXX167@qq.com' # 发件人邮箱账号
authorization = 'spiXXXXXXXidj' # QQ邮箱授权码
server.login(sender, authorization) # 括号中对应的是发件人邮箱账号、邮箱密码
mailboxContainer = MIMEMultipart() # 创建混合类型容器
mailboxContainer['Subject'] = "测试python发送邮件" # 邮箱主题
mailboxContainer['From'] = sender # 邮箱发送人
receiver_to = ['yXXo@XXXXX.com']
mailboxContainer["To"] = ",".join(receiver_to) # 邮箱接收人
receiver_cc = []
mailboxContainer['Cc'] = ",".join(receiver_cc) # 邮箱抄送人
mail_msg = """
Python 邮件发送测试...
图片演示:
"""
mailboxContainer.attach(MIMEText(mail_msg, 'html', 'utf-8'))
with open(r".\h5_img.jpg", "rb") as f:
msg = f.read()
msgImage = MIMEImage(msg)
msgImage.add_header('Content-ID', '
mailboxContainer.attach(msgImage)
receiver = receiver_to + receiver_cc # 接收邮箱的人(包含接收和抄送)
server.sendmail(sender, receiver, mailboxContainer.as_string())
server.quit()
接收结果如下:
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtpHost = "smtp.qq.com" # 邮件服务器地址
port = 465 # 邮件服务器端口
server = smtplib.SMTP_SSL(smtpHost, port)
sender = '41XXXX7@qq.com' # 发件人邮箱账号
authorization = 'spXXXXXXdj' # QQ邮箱授权码
server.login(sender, authorization) # 括号中对应的是发件人邮箱账号、邮箱密码
mailboxContainer = MIMEMultipart() # 创建混合类型容器
mailboxContainer['Subject'] = "带附件的邮箱" # 邮箱主题
mailboxContainer['From'] = sender # 邮箱发送人
receiver_to = ['yXXX@XXXXX.com']
mailboxContainer["To"] = ",".join(receiver_to) # 邮箱接收人
receiver_cc = []
mailboxContainer['Cc'] = ",".join(receiver_cc) # 邮箱抄送人
mailboxContainer.attach(MIMEText('测试带附件的邮箱', "plain", "utf-8"))
with open(r".\text.txt", "rb") as f:
msg = f.read()
att1 = MIMEText(msg, 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="text.txt"' # 这里的filename可以任意写,写什么名字,邮件附件中显示什么名字
mailboxContainer.attach(att1)
with open(r".\h5_img.jpg", "rb") as f:
msg = f.read()
att2 = MIMEText(msg, 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2.add_header('content-disposition', 'attachment', filename='h5.jpg') # 与上面注释代码功能一样
mailboxContainer.attach(att2)
receiver = receiver_to + receiver_cc # 接收邮箱的人(包含接收和抄送)
server.sendmail(sender, receiver, mailboxContainer.as_string())
server.quit()
接收结果如下:
import os
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from utils.file import file
class SMTP:
def __init__(self, smtp_host="smtp.qq.com", port=465):
# 连接邮件服务器
self.__server = smtplib.SMTP_SSL(smtp_host, port)
self.__sender = None # 发件人邮箱账号
self.__mailboxContainer = MIMEMultipart() # 创建邮箱容器
self.__receiver = []
def quit(self):
self.\_\_server.quit()
def login(self, account, authorization):
"""登录邮箱服务器"""
self.\_\_sender = account
self.\_\_server.login(account, authorization) # 括号中对应的是发件人邮箱账号、邮箱密码
def add\_subject(self, subject):
"""添加邮件主题"""
self.\_\_mailboxContainer\['Subject'\] = subject # 邮箱主题
def add\_receiver(self, receiver\_to: list, receiver\_cc: list = None):
"""
添加邮件接收人
receiver\_to:收件人
receiver\_cc:抄送人
"""
self.\_\_mailboxContainer\["From"\] = self.\_\_sender
self.\_\_mailboxContainer\["To"\] = ",".join(receiver\_to) # 邮箱接收人
self.\_\_mailboxContainer\['Cc'\] = ",".join(receiver\_cc) # 邮箱抄送人
self.\_\_receiver = receiver\_to + receiver\_cc
def add\_content(self, content, mail\_type="plain", append\_imgs: list = None):
"""
添加邮箱内容
content:邮箱内容
mail\_type:内容的类型
append\_imgs:当为html类型时追加图片内容
"""
if mail\_type != "html" and append\_imgs is not None:
raise ValueError(f"main\_type的值不为html,但append\_img不是空")
if mail\_type == "html" and append\_imgs is not None:
for append\_img in append\_imgs:
img\_tag = f"<p><img src='cid:image{append\_imgs.index(append\_img)}'></p>"
content += img\_tag
# 读取图片信息
with open(append\_img, "rb") as f:
msg = f.read()
msgImage = MIMEImage(msg)
# 定义图片 ID,在 HTML 文本中引用
msgImage.add\_header('Content-ID', f'<image{append\_imgs.index(append\_img)}>')
self.\_\_mailboxContainer.attach(msgImage)
self.\_\_mailboxContainer.attach(MIMEText(content, mail\_type, "utf-8"))
def add\_attach(self, file\_path):
"""添加单个附件"""
if not os.path.exists(file\_path):
raise ValueError(f"文件【{file\_path}】不存在")
if not os.path.isfile(file\_path):
raise ValueError(f"【{file\_path}】不是文件")
# 构造文本附件
with open(file\_path, "rb") as f:
msg = f.read()
att = MIMEText(msg, 'base64', 'utf-8')
att\["Content-Type"\] = 'application/octet-stream'
filename = file.get\_path\_last\_name(file\_path)
att\["Content-Disposition"\] = f'attachment; filename="{filename}"' # 这里的filename可以任意写,写什么名字,邮件附件中显示什么名字
self.\_\_mailboxContainer.attach(att)
def add\_attachs(self, file\_paths: list):
"""添加多个附件"""
for file\_path in file\_paths:
self.add\_attach(file\_path)
def send(self):
"""发送邮件"""
self.\_\_server.sendmail(self.\_\_sender, self.\_\_receiver, self.\_\_mailboxContainer.as\_string())
if __name__ == '__main__':
mailbox = SMTP()
# 登录邮箱服务器
account = '418XXXX167@qq.com'
authorization = 'spiXXXXXidj' # QQ邮箱授权码
mailbox.login(account, authorization)
# 添加邮箱主题
mailbox.add\_subject("使用SMTP封装类发送的邮件")
# 添加邮箱接收人
receiver\_to = \['yXXXo@XXX.com'\] # 收件人
receiver\_cc = \['41XXX7@qq.com'\] # 抄送人
mailbox.add\_receiver(receiver\_to, receiver\_cc)
# 添加邮箱内容
mail\_content = """
<p>Python 邮件发送测试...</p>
<p>追加图片如下</p>
"""
append\_imgs = \[r".\\h5\_img.jpg", r".\\doudou.png"\]
mailbox.add\_content(mail\_content, mail\_type="html", append\_imgs=append\_imgs)
# 添加附件
mailbox.add\_attach("text.txt")
mailbox.add\_attachs(\[r".\\h5\_img.jpg", r".\\doudou.png"\])
# 发送邮箱
mailbox.send()
发送结果如下
手机扫一扫
移动阅读更方便
你可能感兴趣的文章