好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

如何用python进行邮件发送

  使用Python调用邮件服务器发送邮件,使用的协议是 SMTP(Simple Mail Transfer Protocol) ,下图为使用 TCP/IP 基于 SMTP 发送邮件的过程示意图:

          

SMTP协议工作原理:

  SMTP 工作在两种情况下:一是电子邮件从用户端传输到服务器:二是从某一个 MTA(Message Transfer Agent) 传输到另一个 MTA 。 SMTP 也是请求/响应协议,命令和响应都是基于 NVT ASCII 文本,并以 CR 和 LF 符结束。响应包括一个表示返回状态的三位数字代码。 SMTP 在 TCP 协议 25号 端口监听连续请求。

SMTP连接和发送过程

 (1)建立TCP 连接。    (2)客户端发送HELO命令以标识发件人自己的身份,然后客户通过发送MIAL命令标识出电子邮件的发起人;服务器端正希望以OK作为响应,表明准备接收。    (3)客户端发送RCPT命令,以标识该电子邮件的计划接收人,可以有多个RCPT行;服务器端则表示是否愿意为收件人接收邮件。    (4)协商结束,发送邮件,用命令DATA发送。    (5)以“.”号表示结束输入内容一起发送出去,结束此次发送,用QUIT命令退出。

Python使用SMTP发送邮件

  在python中,发送邮件主要包括email 和smtplib,其中email 实现邮件构造,smtplib实现邮件发送。在smtplib库中,主要主要用smtplib.SMTP()类,用于连接SMTP服务器,发送邮件。SMTP类中常用方法如

方法

描述

SMTP.set_debuglevel(level) 设置输出debug调试信息,默认不输出 SMTP.docmd(cmd[, argstring]) 发送一个命令到SMTP服务器 SMTP.connect([host[, port]]) 连接到指定的SMTP服务器 SMTP.helo([hostname]) 使用helo指令向SMTP服务器确认你的身份 SMTP.ehlo(hostname) 使用ehlo指令像ESMTP(SMTP扩展)确认你的身份 SMTP.ehlo_or_helo_if_needed() 如果在以前的会话连接中没有提供ehlo或者helo指令,这个方法会调用ehlo()或helo() SMTP.has_extn(name) 判断指定名称是否在SMTP服务器上 SMTP.verify(address) 判断邮件地址是否在SMTP服务器上 SMTP.starttls([keyfile[, certfile]]) 使SMTP连接运行在TLS模式,所有的SMTP指令都会被加密 SMTP.login(user, password) 登录SMTP服务器 SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])

发送邮件

from_addr:邮件发件人

to_addrs:邮件收件人

msg:发送消息

SMTP.quit() 关闭SMTP会话 SMTP.close() 关闭SMTP服务器连接

  python中通过SMTP发送邮件主要包括以下几个步骤(以qq邮箱为例):

  1. 开通邮箱SMTP服务,获取邮箱授权码,邮箱SMTP开通路径:邮箱设置/账户/POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

                 

  2. 编辑邮件内容,主要包括三部分内容:信封,首部和正文;其中信封包括发送邮箱,接收邮箱等;

  3. 初始化配置信息,调用SMTP发送邮件

  代码实现如下所示,其中python版本为3.7:

 1 import  smtplib
 2 import email.utils
 3 from email.mime.text import MIMEText
 4 
 5 class Msg():
 6     def __init__(self):
 7         pass
 8 
 9     @staticmethod
10     def creat_msg():
11         # Creat mail information
12         msg = MIMEText(‘Come on‘, ‘plain‘, ‘utf-8‘)
13         msg[‘From‘] = email.utils.formataddr((‘Author‘, ‘[email protected]‘))
14         msg[‘To‘] = email.utils.formataddr((‘Recipient‘, ‘[email protected]‘))
15         msg[‘Subject‘] = email.utils.formataddr((‘Subject‘, ‘Good good study, day day up!‘))
16 
17         return msg
18 
19 class EmailServer():
20     def __init__(self):
21         pass
22 
23     @staticmethod
24     def config_server():
25         # Configure mailbox
26         config = dict()
27         config[‘send_email‘]= ‘[email protected]‘
28         config[‘passwd‘] = ‘xxxxxxxxxx‘
29         config[‘smtp_server‘] = ‘smtp.qq.com‘
30         config[‘target_email‘] = ‘[email protected]‘
31         return config
32 
33     def send_email(self):
34         # Use smtp to send email to the target mailbox
35         msg = Msg.creat_msg()
36         config = self.config_server()
37 
38         server = smtplib.SMTP()
39         server.connect(host=config[‘smtp_server‘], port=25)
40         server.login(user=config[‘send_email‘], password=config[‘passwd‘])
41         server.set_debuglevel(True)
42 
43         try:
44             server.sendmail(config[‘send_email‘],
45                             [config[‘target_email‘]],
46                             msg.as_string())
47         finally:
48             server.quit()
49 
50 if __name__ == ‘__main__‘:
51     emailServer = EmailServer()
52     emailServer.send_email()

  发送邮件过程跟踪如下:

  经过测试,从QQ邮箱向163邮箱可正常发送邮件,从163邮箱发送到QQ邮箱则会进入垃圾箱,翻阅了不少资料,目前还没有解决如何摆脱垃圾箱的困扰,如有知道的朋友,可在评论区解惑,不甚感谢~ 

参考文献:

(1)https://blog.51cto.com/lizhenliang/1875330

(2)TCP/IP详解卷1:协议

查看更多关于如何用python进行邮件发送的详细内容...

  阅读:21次