如何用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类中常用方法如
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:协议 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |