使用Python发送多封邮件,百分百可用

如何使用python通过QQ邮箱发送邮件,具体实现方式如下:

# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
'''
SMTP_host:邮件服务器,
from_account:邮箱账号/发送者邮箱
from_passwd:邮箱密码
to_account:接收者邮箱,是一个list
subject:邮件主题
content:邮件内容
'''
def send_email(SMTP_host, from_account, from_passwd, to_account, subject, content):
    # create msg
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')  # subject
    msg['From'] = from_account
    msg['To'] = ';'.join(to_account)

    try:
        #需要使用支持SSL协议的方法,使用smtplib.SMTP邮件只能163之间发送,无法和QQ等其他邮箱互发
        email_client = smtplib.SMTP_SSL(SMTP_host, '465')
        email_client.login(from_account, from_passwd)
        email_client.sendmail(from_account, to_account, msg.as_string())
    except smtplib.SMTPException as e:
        print(e)
        print('邮件发送失败!')
    except socket.gaierror as e:
        print(e)
        print('邮件服务器链接失败!')
    else:
        email_client.quit()
        print('成功发送%s封邮件.' % len(to_account))

if __name__ == "__main__":
    from_account = '4********[email protected]'
    #每个邮箱服务器对应的授权不一样的,得到的密码也不一样。这里的是授权密码,不是登录密码。
    from_passwd = '**************'
    to_account = ['4*********[email protected]','l*********[email protected]']
    #邮件发送的服务器
    SMTP_host = 'smtp.qq.com'
    subject = '发送邮件'
    content = '''
    请注意,请注意:
        发送邮件~~~~~~
        发送~~~
        发送成功了~~~~~~~
    '''
    send_email(SMTP_host, from_account, from_passwd, to_account, subject, content)

你可能感兴趣的:(python)