python 发送邮件及附件

python3 同时被 2 个专栏收录
24 篇文章 0 订阅
1 篇文章 0 订阅

用授权码登录发送邮件及附件

需要对邮件进行POP3/SMTP服务设置,例如qq邮箱:

特别提示- --->    千万不要泄漏自己的授权码 

这里的邮箱的域名与端口根据自己的实际邮箱去填写(这是qq邮箱)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


def send_email(smtp_host, smtp_port, sendAddr, password, recipientAddrs, subject='', content=''):
    '''
    :param smtp_host: 域名
    :param smtp_port: 端口
    :param sendAddr: 发送邮箱
    :param password: 邮箱密码
    :param recipientAddrs: 发送地址
    :param subject: 标题
    :param content: 内容
    :return: 无
    '''
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = sendAddr
    msg['to'] = recipientAddrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)

    # 添加附件地址
    part = MIMEApplication(open(r'C:\Users\zsjw_pachong01\Desktop\线上抓取指标统计表(1).xlsx', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="线上抓取指标统计表(1).xlsx")  # 发送文件名称
    msg.attach(part)

    try:
        smtpSSLClient = smtplib.SMTP_SSL(smtp_host, smtp_port)  # 实例化一个SMTP_SSL对象
        loginRes = smtpSSLClient.login(sendAddr, password)  # 登录smtp服务器
        print(f"登录结果:loginRes = {loginRes}")  # loginRes = (235, b'Authentication successful')
        if loginRes and loginRes[0] == 235:
            print(f"登录成功,code = {loginRes[0]}")
            smtpSSLClient.sendmail(sendAddr, recipientAddrs, str(msg))
            print(f"mail has been send successfully. message:{str(msg)}")
            smtpSSLClient.quit()
        else:
            print(f"登陆失败,code = {loginRes[0]}")
    except Exception as e:
        print(f"发送失败,Exception: e={e}")


try:
    subject = 'Python 测试邮件'
    content = '这是一封来自 Python 编写的测试邮件。'
    send_email('smtp.qq.com', 465, '发送邮箱', '邮箱授权码', '接收邮箱', subject, content)
except Exception as err:
    print(err)

如果不需要附件可以把以下代码注释掉即可

part = MIMEApplication(open(r'C:\Users\zsjw_pachong01\Desktop\线上抓取指标统计表(1).xlsx', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="线上抓取指标统计表(1).xlsx")  # 发送文件名称
msg.attach(part)

或者参考这段优化的代码

# 添加文件 emailSender.py
import smtplib
import datetime
from email.mime.text import MIMEText


class EmailSender(object):
    def __init__(self):
        self.smtp_host = "smtp.qq.com"  # 发送邮件的smtp服务器(从QQ邮箱中取得)
        self.smtp_user = "xxx@qq.com"  # 用于登录smtp服务器的用户名,也就是发送者的邮箱
        self.smtp_pwd = "xxxxxxxxxxx"  # 授权码,和用户名user一起,用于登录smtp, 非邮箱密码
        self.smtp_port = 465  # smtp服务器SSL端口号,默认是465
        self.sender = xxx@qq.com  # 发送方的邮箱

    def send_email(self, toLst, subject, body):
        '''
        发送邮件
        :param toLst: 收件人的邮箱列表["123456@qq.com", "987654@qq.com"]
        :param subject: 邮件标题
        :param body: 邮件内容
        :return:
        '''
        message = MIMEText(body, 'plain', 'utf-8')  # 邮件内容,格式,编码
        message['From'] = self.sender               # 发件人
        message['To'] = ",".join(toLst)             # 收件人列表
        message['Subject'] = subject                # 邮件标题
        try:
            smtpSSLClient = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port)   # 实例化一个SMTP_SSL对象
            loginRes = smtpSSLClient.login(self.smtp_user, self.smtp_pwd)      # 登录smtp服务器
            print(f"登录结果:loginRes = {loginRes}")    # loginRes = (235, b'Authentication successful')
            if loginRes and loginRes[0] == 235:
                print(f"登录成功,code = {loginRes[0]}")
                smtpSSLClient.sendmail(self.sender, toLst, message.as_string())
                print(f"mail has been send successfully. message:{message.as_string()}")
                smtpSSLClient.quit()
            else:
                print(f"登陆失败,code = {loginRes[0]}")
        except Exception as e:
            print(f"发送失败,Exception: e={e}")

调用如下:

email = EmailSender()
toSendEmailLst = ['pylemonorg@gmail.com']
finishTime = datetime.now()
subject = f"我是标题, finishedTime = {finishTime}"
body = "我是内容。。。"
email.send_email(toSendEmailLst, subject, body)

 

用户名,密码登录发送邮件和附件

如果只发文本内容,不需要发附件把以下注释掉即可

part = MIMEApplication(open(r'C:\Users\zsjw_pachong01\Desktop\线上抓取指标统计表(1).xlsx', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="线上抓取指标统计表(1).xlsx")  # 发送文件名称
msg.attach(part)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_email(smtpHost, sendAddr, password, recipientAddrs, subject='', content=''):
    '''
    :param smtpHost: 域名
    :param sendAddr: 发送邮箱
    :param password: 邮箱密码
    :param recipientAddrs: 发送地址
    :param subject: 标题
    :param content: 内容
    :return: 无
    '''
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = sendAddr
    msg['to'] = recipientAddrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)

    # 添加附件地址
    part = MIMEApplication(open(r'C:\Users\zsjw_pachong01\Desktop\线上抓取指标统计表(1).xlsx', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="线上抓取指标统计表(1).xlsx")  # 发送文件名称
    msg.attach(part)

    smtp = smtplib.SMTP()
    smtp.connect(smtpHost, '25')
    smtp.login(sendAddr, password)
    smtp.sendmail(sendAddr, recipientAddrs, str(msg))
    print("发送成功!")
    smtp.quit()

try:
    subject = 'Python 测试邮件'
    content = '这是一封来自 Python 编写的测试邮件。'
    send_email('smtp.qq.com', 'send_email_user', 'password', 'to_email_user', subject, content)
except Exception as err:
    print(err)

 

  • 7
    点赞
  • 8
    评论
  • 12
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 8 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:黑客帝国 设计师:我叫白小胖 返回首页

打赏作者

pylemon

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值