python3实现邮件的发送

时间:2022-07-22
本文章向大家介绍python3实现邮件的发送,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用的email和smtplib模块,这里简单介绍下smtplib.SMTP()类

SMTP.set_debuglevel(level):设置输出debug调试信息,默认不输出
SMTP.connect([host[, port]]):连接到指定的SMTP服务器
SMTP.login(user, password):登录SMTP服务器
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]):from_addr:邮件发件人,to_addrs:邮件收件人,msg:发送消息
SMTP.quit():关闭SMTP会话
SMTP.close():关闭SMTP服务器连接

最简单的邮件实现

email用来构造邮件

smtplib用来发送邮件

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



mail_host = "smtp.xxx.com"
mail_user = "xxx@xxxx.com"
mail_pass = "xxxxx"

sender = "xxx@xxx.com"
receivers = ['xxx@xxx.com']

content = '你是一只傻狗吗?是的!'
title = '傻狗'


def sendEmail():
    msg = MIMEText(content,'plain','utf-8')
    msg['From'] = "{}".format(sender)
    msg['To'] = ",".join(receivers)
    msg['Subject'] = title

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host,465)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender,receivers,msg.as_string())
        print('mail send successful.')
    except smtplib.SMTPException as e:
        print(e)

if __name__ == '__main__':
    sendEmail()

– 注意

这里的msg = MIMEText(content,’plain’,’utf-8′),content是要发送的邮件内容,第二个参数是MIME的subtype,这里是plain,其他的还有html,带附件的邮件,utf-8保证语言多样性。

login()用来登陆邮箱,sendmail()用来发邮件,as_string()用来把MIMEText转换成str。

下面使用Class对象方法来改善下这个程序

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


class SendMail():
    def __init__(self,mail_host,mail_user,mail_pass,sender,receivers,content,title):
        self.mail_host = mail_host
        self.mail_user = mail_user
        self.mail_pass = mail_pass
        self.sender = sender
        self.receivers = receivers
        self.content = content
        self.title = title

    def sendEmail(self):
        msg = MIMEText(content,'plain','utf-8')
        msg['From'] = "{}".format(sender)
        msg['To'] = ",".join(receivers)
        msg['Subject'] = title
        try:
            smtpObj = smtplib.SMTP_SSL(mail_host,465)
            smtpObj.login(mail_user,mail_pass)
            smtpObj.sendmail(sender,receivers,msg.as_string())
            print('mail send successful.')
        except smtplib.SMTPException as e:
            print(e)

if __name__ == '__main__':
    mail_host = "smtp.xxx.com"
    mail_user = "xxxx@xxx.com"
    mail_pass = "xxxxx"
    sender = "xxxx@xxx.com"
    receivers = ['xxxxxxx@xx.com','xxx@xxx.com','xxxx@xx.com']
    content = '你是一只傻狗吗?是的!'
    title = '傻狗'
    m = SendMail(mail_host,mail_user,mail_pass,sender,receivers,content,title)
    m.sendEmail()

再来优化下,去掉一些不必要的,另外再改成可以通过命令行传参的方式

未完待续。。。。。。