首页 > 解决方案 > 如何使用 Python 中的 smtplib 发送文本或 word 文件?

问题描述

我在谷歌上搜索过,但这些例子对于像我这样的初学者来说有点难。如果有任何简单的例子......我知道如何发送基于 html 的消息

标签: pythonsmtpsmtpclientsmtplib

解决方案


import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate





def send_mail(send_from,password send_to, subject, text, file=None,
              server="127.0.0.1"):

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))


    with open(file, "rb") as fil:
        part = MIMEApplication(
            fil.read(),
            Name=basename(file)
        )
    # After the file is closed
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file)
    msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(send_from, password )
    text = msg.as_string()
    server.sendmail(send_from, send_to, text)
    server.quit()

send_mail('From','Password','ToMail','Subject','msg',r'FullPath')

推荐阅读