如何使用Python中的smtplib发送文本或文字文件?

时间:2018-08-09 11:25:32

标签: python smtp smtpclient smtplib

我在Google上进行了搜索,但是这些示例对于像我这样的初学者来说很难。如果有任何简单的示例...我知道如何发送基于html的消息

1 个答案:

答案 0 :(得分:1)

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')