smtplib 自动发邮件 同时发多个文件 至 多收件人

smtplib 自动发邮件 同时发多个文件 至 多收件人


话不多说直接上代码

初级版本

这个的功能是给多人发邮件,不带附件的。

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 14:45:32 2021

@author: dujidan
"""

import time
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def send_single_mail(receivers_list, mail_title, mail_content):
    """
    send mail with word/pdf attachment for a person
    """
    sender_mail='123456@qq.com'
    pwd='123456'
    #邮箱smtp服务器  固定的
    host_server = 'smtp.qq.com'  # 去邮箱设置里找
    #邮件正文内容
    msg = MIMEMultipart()
    msg["Subject"] = Header(mail_title, 'utf-8')
    msg["From"] = sender_mail
    msg["To"] = Header('; '.join(receivers_list), 'utf-8') 
    msg.attach(MIMEText(mail_content, 'html', 'utf-8'))

    # 邮箱登录
    conn_success = False
    retry_counts = 0
    while not conn_success and retry_counts < 3:
        try:
            #E-mail ssl登录
            smtp = SMTP_SSL(host_server)
            #set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
            smtp.set_debuglevel(0)
            smtp.ehlo(host_server)
            smtp.login(sender_mail, pwd)
            conn_success = True
            smtp.sendmail(sender_mail, receivers_list, msg.as_string())
        except Exception as conn_exp:
            # logger.error(conn_exp)
            print(conn_exp)
            retry_counts += 1
            time.sleep(1)
        finally:
            smtp.quit()


if __name__ == '__main__':
    receivers_list = ['123456@qq.com']  # 接收者
    mail_title = '我是标题'          # 标题
    mail_content = '我是正文内容'    # 正文部分

    send_single_mail(receivers_list, mail_title, mail_content)
    print(f'successed')

进阶版本

这个在上一个的基础上,添加了发送附件的内容;并且可以将发送后的附件移动到其他指定位置,方便查看哪些发送成功了。

# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 14:16:55 2021

@author: dujidan
"""


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import os
from os import path, listdir, mkdir, rename
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def send_single_mail(receivers, file_list, mail_title, mail_content, flag, aim_dir):
    """
    send mail with file attachment for a person,and move file to other place
    """
    # 发件人 邮箱 密码
    sender_mail='123456@qq.com'
    pwd='123456'

    #邮箱smtp服务器  固定的
    host_server = 'smtp.qq.com'

    #邮件正文内容
    msg = MIMEMultipart()
    msg["Subject"] = Header(mail_title, 'utf-8')  # 邮件标题
    msg["From"] = sender_mail
    msg["To"] = Header('; '.join(receivers), 'utf-8') # 接收者
    msg.attach(MIMEText(mail_content, 'html', 'utf-8'))  # 发送的内容

    # 构造附件1,传送当前目录下的 test.pdf 文件
    move_file_list = []
    for file_1 in file_list:
        att1 = MIMEText(open(file_1, 'rb').read(), 'base64', 'utf-8')
        att1.add_header('Content-Disposition', 'attachment', filename=file_1.split('/')[-1]) # 发送混合邮件
        msg.attach(att1)
        move_file_list.append( (file_1, file_1.replace(flag, aim_dir[1:])) )

    # 邮箱登录
    conn_success = False
    retry_counts = 0
    while not conn_success and retry_counts < 3:
        try:
            #E-mail ssl登录
            smtp = SMTP_SSL(host_server)
            #set_debuglevel() 是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
            smtp.set_debuglevel(0)
            smtp.ehlo(host_server)
            smtp.login(sender_mail, pwd)
            conn_success = True
            smtp.sendmail(sender_mail, receivers, msg.as_string())
            # 插入数据
            # move the successful mail file
            top_report_dir = path.dirname(path.dirname(file_list[0]))
            if not path.exists(top_report_dir + aim_dir):
                mkdir(top_report_dir + aim_dir)
            for source_file, target_file in move_file_list:
                rename(source_file, target_file)
        except Exception as conn_exp:
            print(conn_exp)
            retry_counts += 1
            time.sleep(1)
        finally:
            smtp.quit()
if __name__ == '__main__':
    receivers = ['receivers@qq.com']
    file_list = ['./send_file.txt']
    mail_title = '邮件标题'
    mail_content = '邮件内容'
    flag = '原目录'
    aim_dir = '目的目录'
    send_single_mail(receivers, file_list, mail_title, mail_content, flag, aim_dir)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值