Python发送Email电子邮件代码
我的站长站
2023-11-13
共人阅读
本文使用 Python 内置库实现邮件发送功能,支持普通文本、HTML 格式邮件,基于 SMTP 协议对接主流邮箱服务商(QQ 邮箱、163 邮箱等)。代码包含账号配置、SSL 加密连接、附件发送、异常捕获,讲解授权码配置要点,适配消息通知、告警推送、报表分发等场景,Python3 环境开箱即用。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.utils import parseaddr, formataddr
import mimetypes
import os
def send_email(smtp_server, username, password, sender, recipients, subject, content, cc, bcc, port=25, sendername=None, attachments=None):
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
if not attachments:
attachments = []
msg = MIMEMultipart()
if sendername:
msg['From'] = _format_addr(sendername + ' <%s>' % sender)
else:
msg['From'] = sender
if isinstance(recipients, str):
recipients = [recipients]
msg['To'] = ",".join(recipients)
if cc:
if isinstance(cc, str):
cc = [cc]
cc_list = [addr for addr in cc if addr not in recipients]
if cc_list:
msg['Cc'] = ",".join(cc_list)
recipients += cc_list
if bcc:
if isinstance(bcc, str):
bcc = [bcc]
bcc_list = [addr for addr in bcc if addr not in recipients]
if bcc_list:
msg['Bcc'] = ",".join(bcc_list)
recipients += bcc_list
msg['Subject'] = Header(subject, 'utf-8').encode()
text_part = MIMEText(content, 'html', 'utf-8')
msg.attach(text_part)
for attachment in attachments:
file_path = attachment["path"]
if not os.path.isfile(file_path):
print("附件文件不存在:{}".format(file_path))
continue
try:
with open(file_path, "rb") as f:
mime_type, encoding = mimetypes.guess_type(file_path)
if mime_type is None:
mime_type = 'application/octet-stream'
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment', filename=attachment["filename"])
part.add_header('Content-Type', mime_type)
msg.attach(part)
except FileNotFoundError as e:
print("文件未找到:{}".format(e))
except Exception as e:
print("附件读取失败:{}".format(e))
try:
if str(port) == "25":
server = smtplib.SMTP(smtp_server, port)
else:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(username, password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()
print("邮件发送成功!")
except Exception as e:
print("邮件发送失败:{}".format(e))
smtp_server = "smtp.aliyun.com"
username = "[email protected]"
password = "password"
sender = "[email protected]"
recipients = "[email protected]"
cc = ["[email protected]","[email protected]"]
bcc = ""
subject = "title"
content = "content"
n = "name"
port = 25
attachments = [{"filename":"申请单.xlsx","path":"C:/申请单.xlsx"},
{"filename": "新课标.docx", "path": "D:/新课标.docx"},
{"filename": "笨笨狗.pdf", "path": "D:/books/笨笨狗.pdf"}]
send_email(smtp_server, username, password, sender, recipients, subject, content, cc,bcc,port=port, sendername=n, attachments=attachments)