Python 代码实现电子邮件发送功能,支持附件发送

Python 代码实现电子邮件发送功能,支持附件发送

破代码一份,最近调整邮件发送脚本,抽出来共享下。

import os
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# a@b.c -> smtp.b.c 个人邮箱大部分可以这样截取
# 企业邮箱需要设置企业邮箱的 服务商的smtp服务地址
def to_smtp_server(mail):
    data = mail.split("@")
    return "smtp.%s" % data[1]

# 添加文件
def attach_files(msg, files):
    if not files:
        return

    for file_path in files:
        part = MIMEApplication(open(file_path, 'rb').read())
        file_name = os.path.split(file_path)[-1]
        part.add_header('Content-Disposition', 'attachment',filename = file_name)
        msg.attach(part)

def send_mail(sender, password, title, content, files, receiver):

    try:
        msg = MIMEMultipart()

        msg['From'] = formataddr(["", sender]) # 发信人
        msg['To'] = formataddr(["", receiver]) # 收信人
        msg['Subject'] = title                 # 标题

        # 内容
        msg.attach(MIMEText(content, 'plain', 'utf-8'))

        # 附件
        attach_files(msg, files)

        # smtp 服务器
        smtp_svr = to_smtp_server(sender)
        server = smtplib.SMTP_SSL(smtp_svr, 465, timeout=10)
        # server.set_debuglevel(1)

        # 登陆
        server.login(sender, password)

        # 发送
        server.sendmail(sender, [receiver, ], msg.as_string())

        # 退出
        server.quit()

    except Exception as e:
        print("Exception:", e)
        return False

    return True

smtplib 发送邮件代码非常简便,基本上就是填空题,填充好关键数据便可以完成smtp 调用。

对上述代码使用,直接调用 send_mail 即可完成邮件的发送:

if __name__ == '__main__':
    sender, pwd = "10001@qq.com", "10001"
    receiver = "10002@qq.com"
    title = "测试标题"
    content = "测试内容"
    attachs = []

    send_mail(sender, pwd, title, content, attachs, receiver)

(全文完)

(欢迎转载本站文章,但请注明作者和出处 云域 – Yuccn

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注