大家好,我是Samaritan。
如今Python非常热门,对于接触过的朋友可能最大的感受就是它的便利。大家应该都知道了如何使用smtplib和MIMEText轻易地发送一封普通的邮件,而在此基础上今天要分享的是如何构造附件内容,发送一封带有附件的邮件。
需要模块:smtplib和email.MIME
一、 模块介绍:
要完成发送邮件的行为,需要的功能肯定主要分为两部分:构造邮件和发送邮件。在python里我们可以使用2个自带的模块来实现,smtplib和email.mime,直接import导入即可,无需下载。
这里简单看一下官方文档的介绍:
smtplib —SMTP协议客户端
Source code: Lib/smtplib.py
The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and RFC 1869 (SMTP Service Extensions).
SMTP (Simple Mail Transfer Protocol)翻译过来是“简单邮件传输协议”的意思,SMTP 协议是由源服务器到目的地服务器传送邮件的一组规则。显然smtplib可以简单理解为在代码中负责发送邮件的部分。我们会用到已下方法:
import smtplib
server = smtplib.SMTP()
server.connect(host, port)
server.login(username, password)
server.sendmail(sender, to_addr, msg.as_string())
server.quit()
接着再看email.mime:
email.mime: Creating email and MIME objects from scratch
Source code: Lib/email/mime/
This module is part of the legacy (Compat32) email API. Its functionality is partially replaced by the contentmanager in the new API, but in certain applications these classes may still be useful, even in non-legacy code.
Ordinarily, you get a message object structure by passing a