实用向SMTP和EMAIL - 小白也能马上用Python发送带有附件的邮件

大家好,我是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

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值