吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1720|回复: 8
收起左侧

[Python 转载] Python实现发送邮件功能

  [复制链接]
js20184 发表于 2021-11-9 10:23
废话不多数直接上代码
[Python] 纯文本查看 复制代码
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.mime.base import MIMEBase
import smtplib
import os
import datetime



[Python] 纯文本查看 复制代码
'''将Excel作为附件发送邮件'''
    def __init__(self, email_info):
        self.email_info = email_info
        # 使用SMTP_SSL连接端口为465
        self.smtp = smtplib.SMTP_SSL(self.email_info['server'], self.email_info['port'])
        # 创建两个变量
        self._attachements = []
        self._from = ''
    def login(self):
        # 通过邮箱名和smtp授权码登录到邮箱
        self._from = self.email_info['user']
        self.smtp.login(self.email_info['user'], self.email_info['password'])
        print("{0} 邮箱登录完成".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))



[Python] 纯文本查看 复制代码
    def add_attachment(self):
        # 添加附件内容
        # 注意:添加附件内容是通过读取文件的方式加入
        file_path = self.email_info['file_path']
        # print(file_path[1])
        for num in range(0, len(file_path)):
            with open(file_path[num], 'rb') as file:
                filename = os.path.split(file_path[num])[1]
                mime = MIMEBase('application', 'octet-stream', filename=filename)
                mime.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))
                mime.add_header('Content-ID', '<0>')
                mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(file.read())
                encoders.encode_base64(mime)
                # 添加到列表,可以有多个附件内容
                self._attachements.append(mime)
        print("{0} 邮件内容编写完成".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))



[Asm] 纯文本查看 复制代码
    def sendMail(self):
        # 发送邮件,可以实现群发
        msg = MIMEMultipart()
        contents = MIMEText(self.email_info['content'], 'plain', 'utf-8')
        msg['From'] = self.email_info['user']
        msg['To'] = self.email_info['to']
        msg['Subject'] = self.email_info['subject']
        if 'cc' in self.email_info and 'bc' in self.email_info:
            msg['Cc'] = self.email_info['cc']
            msg['Bcc'] = self.email_info['bc']
            rto = self.email_info['to'].split(',') + self.email_info['cc'].split(',') + self.email_info['bc'].split(',')
            for att in self._attachements:
                # 从列表中提交附件,附件可以有多个
                msg.attach(att)
            msg.attach(contents)
            try:
                self.smtp.sendmail(self._from, rto, msg.as_string())

                print('{0} 邮件发送成功,请注意查收'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            except Exception as e:
                print('Error:', e)
        elif 'cc' in self.email_info and 'bc' not in self.email_info:
            msg['Cc'] = self.email_info['cc']
            rto = self.email_info['to'].split(',') + self.email_info['cc'].split(',')
            for att in self._attachements:
                # 从列表中提交附件,附件可以有多个
                msg.attach(att)
            msg.attach(contents)
            try:
                self.smtp.sendmail(self._from, rto, msg.as_string())

                print('{0} 邮件发送成功,请注意查收'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            except Exception as e:
                print('Error:', e)
        elif 'cc' not in self.email_info and 'bc' in self.email_info:
            msg['Bcc'] = self.email_info['bc']
            rto = self.email_info['to'].split(',') + self.email_info['bc'].split(',')
            for att in self._attachements:
                # 从列表中提交附件,附件可以有多个
                msg.attach(att)
            msg.attach(contents)
            try:
                self.smtp.sendmail(self._from, rto, msg.as_string())

                print('{0} 邮件发送成功,请注意查收'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            except Exception as e:
                print('Error:', e)
        else:
            rto = self.email_info['to'].split(',')
            for att in self._attachements:
                # 从列表中提交附件,附件可以有多个
                msg.attach(att)
            msg.attach(contents)
            try:
                self.smtp.sendmail(self._from, rto, msg.as_string())

                print('{0} 邮件发送成功,请注意查收'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            except Exception as e:
                print('Error:', e)



[Asm] 纯文本查看 复制代码
    def close(self):
        # 退出smtp服务
        self.smtp.quit()
        print('{0} 任务结束,退出登录'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

免费评分

参与人数 4吾爱币 +8 热心值 +4 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
GhostCN_Z + 1 + 1 最简:https://cloud.tencent.com/developer/article/1855997
浩哥. + 1 + 1 感谢您的宝贵建议,我们会努力争取做得更好!
punnpkin + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

菱角 发表于 2021-11-9 12:34
yagmail发邮件好简单
我今天是大佬 发表于 2021-11-9 13:59
ye1209mx 发表于 2021-11-9 14:13
感谢发布原创作品,吾爱破解论坛因你更精彩!
GhostCN_Z 发表于 2021-11-9 16:23
最简
https://cloud.tencent.com/developer/article/1855997
 楼主| js20184 发表于 2021-11-9 17:17
菱角 发表于 2021-11-9 12:34
yagmail发邮件好简单

感谢提醒
 楼主| js20184 发表于 2021-11-9 17:17
GhostCN_Z 发表于 2021-11-9 16:23
最简
https://cloud.tencent.com/developer/article/1855997

感谢分享,我研究下你这个,我写这个需要配合部分业务场景,已经看下能不能结合
 楼主| js20184 发表于 2021-11-9 17:18

感谢提醒,又学到新的东西,哈哈哈
zhgang908 发表于 2021-11-9 21:13
Mozilla/5.0 (Windows NT 6.1; rv:94.0) Gecko/20100101 Firefox/94.0
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 11:37

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表