[Python] 纯文本查看 复制代码
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 = "abc@aliyun.com"
password = "password"
sender = "abc@aliyun.com"
recipients = "abc@abc.cn"
cc = ["abc@126.com","abc@139.com"]
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)