首页 > 编程语言 > 详细

python自动发送邮件

时间:2019-08-10 15:47:13      阅读:85      评论:0      收藏:0      [点我收藏+]

  我一直想学习用python自动发送邮件,但是由于太懒了就耽误下来了。今天中午吃完饭我的兴趣又来了,所以学会了python发送邮件的基本操作。

  基本操作的代码如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header


def send_email(SMTP_host, from_account, from_password, to_account, subject, content):
    # 1. 实例化SMTP
    smtp = smtplib.SMTP()

    # 2. 链接邮件服务器
    smtp.connect(SMTP_host)

    # 3. 配置发送邮箱的用户名和密码
    smtp.login(from_account, from_password)

    # 4. 配置发送内容msg
    msg = MIMEText(content, plain, utf-8)
    msg[Subject] = Header(subject, utf-8)
    msg[From] = from_account
    msg[To] = to_account

    # 5. 配置发送邮箱,接受邮箱,以及发送内容
    smtp.sendmail(from_account, to_account, msg.as_string())

    # 6. 关闭邮件服务
    smtp.quit()


if __name__ == __main__:
    from_account = ""
    from_pssword = ""
    to_account = ""
    subject = ""
    content = ""
    send_email("smtp.qq.com", from_account, from_pssword, to_account, subject, content)
    print("邮件发送成功!")

  填入发送者账户及密码、接受者账户、邮件主题及内容后,即可以发送者的名义发送一封邮件至指定的接收者。本代码中的smtplib库是python3自带的库,不用安装。由于我的发送者账户用的是qq邮箱,所以smtp服务器地址是用的qq邮箱的,即smtp.qq.com。

  需要注意的是,发送者密码(from_password)这里有个小坑:这里如果直接填写发送者邮箱的密码,邮件是无法发送成功的。解决方法是在邮箱设置中开启POP3/SMTP服务,并且将from_password用授权码代替。详情参看网址:开启POP3/SMTP服务

  完。

 

python自动发送邮件

原文:https://www.cnblogs.com/potatorain/p/11331511.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!