Python发送邮件

我们在开发程序的时候,有时候需要开发一些自动化的任务,执行完之后,将结果自动的发送一份邮件,python发送邮件使用smtplib模块,是一个标准包,直接import导入使用即可,代码如下:

        import smtplib        
        from email.mime.text import MIMEText
        email_host = 'smtp.163.com'     #邮箱地址
        email_user = 'xxxx@163.com'  # 发送者账号
        email_pwd = 'xxxx'       # 发送者密码
        maillist ='1162704960@qq.com'
        #收件人邮箱,多个账号的话,用逗号隔开
        me = email_user
        msg = MIMEText('邮件发送测试内容')    # 邮件内容
        msg['Subject'] = '邮件测试主题'    # 邮件主题
        msg['From'] = me    # 发送者账号
        msg['To'] = maillist    # 接收者账号列表
        smtp = smtplib.SMTP(email_host,port=25) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
        smtp.login(email_user, email_pwd)   # 发送者的邮箱账号,密码
        smtp.sendmail(me, maillist, msg.as_string())
        # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
        smtp.quit() # 发送完毕后退出smtp
        print ('email send success.')

下面是发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username='xxx@xx.com'
email_host = 'smtp.163.com'
passwd='123456'
recv='1162704960@qq.com,1162704960@qq.com'
title='邮件标题'
content='发送邮件测试'
msg = MIMEMultipart()
file='a.txt'
att = MIMEText(open(file,encoding='utf-8').read())
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"'%file
msg.attach(att)
msg.attach(MIMEText(content))#邮件正文的内容
msg['Subject'] = title  # 邮件主题
msg['From'] = username  # 发送者账号
msg['To'] = recv  # 接收者账号列表
#smtp = smtplib.SMTP_SSL(email_host,port=465)#qq邮箱
smtp = smtplib.SMTP_SSL(email_host,port=25)#其他邮箱
smtp.login(username,passwd)
smtp.sendmail(username,recv,msg.as_string())
smtp.quit()

当然,我们可以封装成一个函数,使用的时候,直接调用函数,传入邮箱账号密码,收件人,发件人,标题和内容即可。

            import smtplib            
            from email.mime.text import MIMEText
            def send_mail(username,passwd,recv,title,content,mail_host='smtp.163.com',port=25):
                '''
                发送邮件函数,默认使用163smtp
                :param username: 邮箱账号 xx@163.com
                :param passwd: 邮箱密码
                :param recv: 邮箱接收人地址,多个账号以逗号隔开
                :param title: 邮件标题
                :param content: 邮件内容
                :param mail_host: 邮箱服务器
                :param port: 端口号
                :return:
                '''
                msg = MIMEText(content)    # 邮件内容
                msg['Subject'] = title    # 邮件主题
                msg['From'] = username    # 发送者账号
                msg['To'] = recv    # 接收者账号列表
                smtp = smtplib.SMTP(mail_host,port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
                smtp.login(username, passwd)   # 发送者的邮箱账号,密码
                smtp.sendmail(username, recv, msg.as_string())
                # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
                smtp.quit() # 发送完毕后退出smtp
                print ('email send success.')
                
        email_user = 'xxxx@163.com'  # 发送者账号
        email_pwd = 'xxxxx'       # 发送者密码
        maillist ='1162704960@qq.com'
        title = '测试邮件标题'
        content = '这里是邮件内容'
        send_mail(email_user,email_pwd,maillist,title,content)

完善版:

import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
class SendMail(object):
    def __init__(self,username,passwd,recv,title,content,
                 file=None,ssl=False,
                 email_host='smtp.163.com',port=25,ssl_port=465):
        '''
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人,多个要传list ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file: 附件路径,如果不在当前目录下,要写绝对路径,默认没有附件
        :param ssl: 是否安全链接,默认为普通
        :param email_host: smtp服务器地址,默认为163服务器
        :param port: 非安全链接端口,默认为25
        :param ssl_port: 安全链接端口,默认为465
        '''
        self.username = username #用户名
        self.passwd = passwd #密码
        self.recv = recv #收件人,多个要传list ['a@qq.com','b@qq.com]
        self.title = title #邮件标题
        self.content = content #邮件正文
        self.file = file #附件路径,如果不在当前目录下,要写绝对路径
        self.email_host = email_host #smtp服务器地址
        self.port = port #普通端口
        self.ssl = ssl #是否安全链接
        self.ssl_port = ssl_port #安全链接端口
    def send_mail(self):
        msg = MIMEMultipart()
        #发送内容的对象
        if self.file:#处理附件的
            file_name = os.path.split(self.file)[-1]#只取文件名,不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开!!!!')
            else:
                att = MIMEText(f,"base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                #base64.b64encode(file_name.encode()).decode()
                new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                #这里是处理文件名为中文名的,必须这么写
                att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)
                msg.attach(att)
        msg.attach(MIMEText(self.content))#邮件正文的内容
        msg['Subject'] = self.title  # 邮件主题
        msg['From'] = self.username  # 发送者账号
        msg['To'] = ','.join(self.recv)  # 接收者账号列表
        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host,port=self.port)
        #发送邮件服务器的对象
        self.smtp.login(self.username,self.passwd)
        try:
            self.smtp.sendmail(self.username,self.recv,msg.as_string())
            pass
        except Exception as e:
            print('出错了。。',e)
        else:
            print('发送成功!')
        self.smtp.quit()


if __name__ == '__main__':
    m = SendMail(
        username='xxx@qq.com',
        passwd='xxxx',
        recv=['1162704960@qq.com','1162704960@qq.com'],
        title='新鞋的发送邮件',
        content='哈哈哈啊哈哈哈哈',
        file=r'C:UsersjniuhanyangDesktop新建 Microsoft Office Excel 工作表.xlsx',ssl=True,
    )
    m.send_mail()

注:如果在发送邮件时报500错误,如下图:

 

这时,按照下面这个链接修改一下电脑DNS配置即可:

http://www.sohu.com/a/194137114_650589

原文地址:https://www.cnblogs.com/feng0815/p/7955084.html