Python 用SMTP发送邮件

一、简介
  上面介绍了传统邮件的生成和解析,这些都是non-internet,也就是不需要网络就可一完成的。那么当生成了邮件,下一步就是发送了,本文就讲解利用SMTP协议发送邮件。
  正如SMTP(Simple Mail Transfer Protocal)名字一样,只能发送简单邮件。上面讲解就是生成的简单邮件,完全可以通过SMTP协议来发送。

二、SMTP使用方法
  Python是通过smtplib模块来实现SMTP的。关于本模块的详细说明,请参考这里
1. 方法流程
  生成message, 连接你的邮箱smtp服务器,登录自己的邮箱帐号, 发送邮件,退出
2. 连接邮箱smtp服务器
  一般各大公司的smtp邮箱服务器网址都是形如:smtp.example.com,如gmail的为smtp.gmail.com
  连接邮箱smtp服务器使用smtplib.SMTP()和smtplib.SMTP_SSL()方法。SMTP_SSL()方法使用了安全socket层。由于我不求甚解,所以更加详细的说明请见文档。我使用的gmail使用的是SMTP_SSL(),所以代码如下:

smtpServer = 'smtp.gmail.com'
server = smtplib.SMTP_SSL(smtpServer)

  由于可能出现异常错误,所以可以用try...except来处理下,如:

import smtplib, sys

smtpServer = 'smtp.gmail.com'
try:
    server = smtplib.SMTP_SSL(smtpServer) #返回SMTP类,所以server是SMTP类的实例
except ConnectionRefusedError:
    print('Server connecting failed')
    sys.exit(1)

3. 登录自己的邮箱帐号
  利用SMTP.login(user, passwd)登录,如:

user = 'myUserName@gmail.com'
passwd = '***' 
server.login(user, passwd)

  在文档中说明了可能出现的异常,最长见的是smtp.SMTPAuthenticationError。另外,passwd也可一通过getpass.getpass()方法获得,这种方法与用户进行交互,用户输入密码,但是不显示,可以保护帐号安全。

import smtplib, sys, getpass

smtpServer = 'smtp.gmail.com'
user = 'myUserName@gmail.com'
passwd = getpass.getpass()

try:
    server = smtplib.SMTP_SSL(smtpServer)
except ConnectionRefusedError:
    print('Server connecting failed')
    sys.exit(1)

try:
    server.login(user, passwd)
except smtp.SMTPAuthenticationError:
    print('Antentication failed, please check your username or password')
    sys.exit(1)

4. 发送邮件及退出
  SMTP提供了两种方法来发送邮件,分别是:SMTP.send_message(), SMTP.sendmail()。简单来说,第一种发送的就是上一节讲的Message类实例,也就是标准的传统邮件;第二种发送的只是一段文字,也就是Content,不包括其他的。下面通过例子演示一下:

import smtplib, sys, getpass
from email.message import Message

smtpServer = 'smtp.gmail.com'
user = 'myUserName@gmail.com'
toAddr = 'toUser@example.com'

passwd = getpass.getpass()

text = """Hi, 
I'm viczzx, this is the message content, reply whenever you saw this.
Thank you!
--viczzx--"""

msg = Message()
msg.set_payload(text)
# 其他header省略

try:
    server = smtplib.SMTP_SSL(smtpServer)
except ConnectionRefusedError:
    print('Server connecting failed')
    sys.exit(1)

try:
    server.login(user, passwd)
except smtp.SMTPAuthenticationError:
    print('Antentication failed, please check your username or password')
    sys.exit(1)
else:
    server.sendmail(user, toAddr, text) #只发送邮件正文
    server.send_message(msg, user, toAddr) #发送Message实例
finally:
    server.quit() #这是必须的!!!

三、 其他的话
  这个smtp小程序是非常简单的,只是把流程上呈现给大家,不过一般情况下这样就足够了。关于SMTP还有其他很多需要注意的地方,比如各种异常处理,由于我在学习的时候没有出现这些问题,因此就没有特别说明,如果需要,请查看相关文档。

原文地址:https://www.cnblogs.com/zixuan-zhang/p/3402819.html