python 使用smtplib发送邮件

一、流程

1.实例化一个连接对象

smtpObj = smtplib.SMTP_SSL(mail_host, 465)

  • mail_host为smtp服务器

2.连接邮箱

smtpObj.login(sender, mail_pwd)

  • sender:发件人的邮箱
  • mail_pwd:发件人邮箱的授权密码

3.编辑内容

3.1实例化一个消息对象:

message = MIMEText(content, ‘plain’, ‘utf-8’)

  • content:邮件正文内容字符串

3.2定义邮件的发件人和接收人

  • message[‘From’] = formataddr((‘发件人邮箱的昵称’, ‘发件人邮箱账号’))
  • message[‘To’] = 收件人邮箱账号’

3.3邮件title

  • message[‘Subject’] = Header(name, ‘utf-8’)
    • name:邮件的标题字符串

4.发送邮件

smtpObj.sendmail(sender, receivers, message.as_string())

  • sender:发件人的邮箱
  • receivers:收件人邮箱列表
  • message.as_string():邮件的格式和呢呢绒

5.示例

mail_host = "smtp.qq.com"  # smtp服务器
sender = '[email protected]'  # 发件人邮箱
mail_pwd = "egasdasdadovig"  # 发件人授权密码

receivers = ['[email protected]', '[email protected]']  # 收件人邮箱(可以自己给自己发邮件)
# 第一个参数为邮件内容,第二个参数为设置文本格式,第三个参数为编码设置
content = '''
邮件的内容部分
''' % (name, withdraw)
message = MIMEText(content, 'plain', 'utf-8')
# 邮件的发件人和接收人
message['From'] = formataddr(('发件人邮箱昵称', '发件人的邮箱'))
message['To'] = '收件人的邮箱'
# 邮件title
message['Subject'] = Header('邮箱标题', 'utf-8')
# print(message.as_string())

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)
    smtpObj.login(sender, mail_pwd)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    smtpObj.quit()
except smtplib.SMTPException as e:
    print(e)
    print("Error: 邮件无法发送")

你可能感兴趣的:(python之路)