python自动发送邮件

  我一直想学习用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服务

  完。

 

posted @ 2019-08-10 14:34  potato226  阅读(166)  评论(0编辑  收藏  举报