使用 Python 的 smtplib 发送电子邮件附件可能具有挑战性,尤其是对于初学者而言。为了提供更易于理解的解释,我们探索了一种全面的方法。
考虑以下代码片段:
import smtplib 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, send_to, subject, text, files=None, server="127.0.0.1"): assert isinstance(send_to, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
分解代码:
这种方法可以让您清楚地了解发送电子邮件所涉及的必要步骤附件。
以上是如何使用Python的smtplib轻松发送电子邮件附件?的详细内容。更多信息请关注PHP中文网其他相关文章!