Python使用smtplib发邮箱

Python使用smtplib发邮箱

首先引入smtplib库email库,为pthon3内置库,若在linux中要pip install email

下面是以自己QQ邮箱发给自己QQ邮箱为例.

发送单人邮箱

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

##### 配置区  #####
mail_host = 'smtp.qq.com'

mail_port = '25'   #win平台上面发

mail_port = '465'   #Linux平台上面发

# 发件人邮箱账号
login_sender = '[email protected]'
# 发件人邮箱授权码而不是邮箱密码,授权码由邮箱官网可设置生成
login_pass = 'xxxxxx'
#邮箱文本内容
str='测试'
#发送者
sendName = ''
#接收者
resName = ''
#邮箱正文标题
title = '叮~~您有一条新的信息,请注意查收~'
########## end  ##########


# 参数是收件人
def sendQQ(receivers):
    msg = MIMEText(str, 'plain', 'utf-8')
    msg['From'] = formataddr([sendName, login_sender])
    # 邮件的标题
    msg['Subject'] = title
    try:
        if mail_port== '25':
            # win平台
            server = smtplib.SMTP(mail_host, mail_port)
            server.login(login_sender, login_pass)
            server.sendmail(login_sender, [receivers, ], msg.as_string())
            print("已发送到" + receivers + "的邮箱中!")
            server.quit()
        else:
            # 服务器
            server = smtplib.SMTP_SSL(mail_host, mail_port)
            server.login(login_sender, login_pass)
            server.sendmail(login_sender, [receivers, ], msg.as_string())
            print("已发送到" + receivers + "的邮箱中!")
            server.quit()

    except smtplib.SMTPException:
        print("发送邮箱失败!")

if __name__ == '__main__':
    sendQQ('[email protected]')  #接收人的QQ邮箱

发送多人邮箱

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 第三方 SMTP服务,如smtp.163.com/smtp.qq.com
mail_host = 'smtp.qq.com'
mail_port = '25'
# 发件人邮箱账号
login_sender = '[email protected]'
# 发件人邮箱授权码而不是邮箱密码,授权码由邮箱官网可设置生成
login_pass = 'xxxxxxxx'

#下面一行是多人发送的情况  收件人邮箱账号,也可以发给多个人['','','']
receivers = ['[email protected]','[email protected]']
#邮箱文本内容
str='测试'
#发送者
sendName = 'xxxxx'
#接收者
resName = 'xxxxx'
#正文标题
title = '叮~~您有新邮件,请注意查收~'
# 这里填写邮件内容
msg = MIMEText(str, 'plain', 'utf-8')
# 发件人邮箱昵称、发件人邮箱账号
msg['From'] = formataddr([sendName, login_sender])

# 收件人邮箱昵称、收件人邮箱账号
#msg['To'] = formataddr([resName, receivers])

#下面一行是多人发送的情况 邮件的标题
msg['To'] =",".join(receivers)

# 邮件的标题
msg['Subject'] = title

try:
    # 设置发件人邮箱中的SMTP服务器
    server = smtplib.SMTP(mail_host, mail_port)
    # 发件人邮箱账号、邮箱授权码
    server.login(login_sender, login_pass)

    #下面一行是多人发送的情况
    server.sendmail(login_sender, msg['To'].split(","), msg.as_string())
    receiver="".join(receivers)
    print("已发送到"+receiver+"的邮箱中!")
    
    server.quit()  # 关闭连接
except smtplib.SMTPException:
    print("发送邮箱失败!")

用途:可用于在服务器运行脚本的时候出错时可以通过邮箱提醒您。

最后可以关注一下我个人微信公众号,不定期更新一些好用的资源以及生活上的点点滴滴~~

Python使用smtplib发邮箱_第1张图片

你可能感兴趣的:(Python)