zoukankan      html  css  js  c++  java
  • python使用smtplib发送邮件

    使用email模块和smtplib模块,内容比较固定,配好了即可实现,代码如下:

    一、普通邮件发送
    import smtplib
    from email.mime.text import MIMEText
    email_host = 'smtp.163.com'     #邮箱地址
    email_user = 'XXX@163.com'  # 发送者账号
    email_pwd = 'XXX'  # 发送者的密码
    maillist ='XXX@XXXX.com'
    #收件人邮箱,多个账号的话,用逗号隔开
    me = email_user
    msg = MIMEText('这是个python测试邮件,不用回复。')    # 邮件内容
    msg['Subject'] = 'python测试'    # 邮件主题
    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.')
    注意
    1. 发送者密码这里不是平时登录邮箱的密码,而是开启登录第三方邮件客户端的授权码。
    2. 多数邮箱的smtp的端口号都是25,个别的请具体确认。

    发邮件的代码封装成函数:
    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 = 'XXX@XXX.com'
    title = '测试邮件标题'
    content = '这里是邮件内容'
    send_mail(email_user, email_pwd, maillist, title, content)
    二、发带附件的邮件
    import smtplib
    #smtplib这个模块是管发邮件
    from email.mime.text import MIMEText
    #构造邮件内容
    from email.mime.multipart import MIMEMultipart
    #发带附件的邮件用的
    email_host = 'smtp.163.com'     #邮箱服务器地址
    email_user = 'XXX@163.com'  # 发送者账号
    email_pwd = 'XXX'
    # 发送者密码是邮箱的授权码,不是登录的密码
    maillist = 'XXX@XXX.com'
    #收件人邮箱,多个账号的话,用逗号隔开
    new_msg = MIMEMultipart()
    #构建了一个能发附件的邮件对象
    new_msg.attach(MIMEText('这是Python测试发邮件的邮件,不要回复'))
    # 邮件内容
    new_msg['Subject'] = 'Python测试邮件带附件'    # 邮件主题
    new_msg['From'] = email_user    # 发送者账号
    new_msg['To'] = maillist    # 接收者账号列表
    att = MIMEText(open('like_report.txt').read())
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="haha.txt"'
    new_msg.attach(att)
    smtp = smtplib.SMTP(email_host,port=25) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
    smtp.login(email_user, email_pwd)   # 发送者的邮箱账号,密码
    smtp.sendmail(email_user, maillist, new_msg.as_string())
    # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
    smtp.quit() # 发送完毕后退出smtp
    print ('email send success.')

    三、封装发送邮件的类并验证
    class SendMail(object):
        def __init__(self,username,passwd,recv,title,content,
                     file=None,
                     email_host='smtp.163.com',port=25):
            self.username = username
            self.passwd = passwd
            self.recv = recv
            self.title = title
            self.content = content
            self.file = file
            self.email_host = email_host
            self.port = port
        def send_mail(self):
            msg = MIMEMultipart()
            #发送内容的对象
            if self.file:#处理附件的
                att = MIMEText(open(self.file).read())
                att["Content-Type"] = 'application/octet-stream'
                att["Content-Disposition"] = 'attachment; filename="%s"'%self.file
                msg.attach(att)
            msg.attach(MIMEText(self.content))#邮件正文的内容
            msg['Subject'] = self.title  # 邮件主题
            msg['From'] = self.username  # 发送者账号
            msg['To'] = self.recv  # 接收者账号列表
            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())
            except Exception as e:
                print('出错了。。',e)
            else:
                print('发送成功!')
        def __del__(self):
            self.smtp.quit()
    
    if __name__ == '__main__':
        m = SendMail(
            username='XXX@163.com',passwd='XXX',recv='XXX@XXX.com',
            title='新鞋的发送邮件',content='哈哈哈啊哈哈哈哈',file='like_report.txt'
        )
        m.send_mail()

    说句实在的,挺喜欢拿别人封装好的类直接拿来用。爽歪歪。



  • 相关阅读:
    mybatis 错误 Invalid bound statement (not found)
    Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.
    bug 记录 Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans
    解决:The Tomcat connector configured to listen on port 8182 failed to start. The port may already be in use or the connector may be misconfigured.
    jquery validate 验证插件 解决多个相同的Name 只验证第一个的方案
    phpStorm+xdebug调试(php7.3)
    小程序视频多个视频播放与暂停
    CSS实现单行、多行文本溢出显示省略号(…)
    Packet for query is too large (4,544,730 > 4,194,304). You can change this value on the server by setting the 'max_allowed_packet' variable.
    idea自动在文件头中添加作者和创建时间
  • 原文地址:https://www.cnblogs.com/nul1/p/11136063.html
Copyright © 2011-2022 走看看