python自动发送邮件---问题归纳

项目场景:

自动发送邮件:有一些未处理的表,自动处理后,由系统自动发送邮件给收件人

问题描述:

1、如何配置服务器?
2、如何解决读取收件人信息的难题?
3、如何读取正文文本?
4、如何发送多个附件且只发送一次?
5、如何发送给收件人?

原因分析:

1、配置服务器:
不同的服务器有不同的地址及端口,使用的时候,根据不同的场景选取不同的服务器
2、读取收件人信息
中文乱码,编解码不一致导致的;
csv文件为例:按文件读取,将每一条读取的数据按行以字典的形式存储起来,以便以后使用
3、读取正文文本
正文文本在本地写完后自动读取上传
判断是否有该文件,没有则退出,有则按文本读取,也需要注意编解码的问题,以防引起中文乱码问题
4、发送多个附件且只发送一次
将多个附件存储在同一个文件夹中,我们需要将文件夹的地址上传,系统自动读取到该文件夹的地址,循环将每一个文件导出
发送一次是只将该方法做循环,不要将所有的方法都做循环
5、发送给收件人
根据读取的收件人信息,填写相应的数据,msg[’From‘],msg[‘To’],msg[‘Subject’],以及服务器的发送方法smtp.sendmail(发件人地址,收件人地址,消息(字符串形式:as_string();))


解决方案:

1、服务器配置:
常用服务器地址及端口
qq:smtp.qq.com:25
163:smtp.163.com:25
密码是邮箱的授权码,不是自己的密码

# 服务器配置
sender_host = "smtp.qq.com:25"  #服务器地址及端口
sender_user = "xxxx@qq.com"
sender_password = "lyuwoewskniwdfhg" #授权码
sender_name="xxxx"

2、如何解决读取收件人信息的难题?

# --------------根据输入的CSV文件,获取通讯录人名和相应的邮箱地址-------
def getAddrBook(addrBook):
    with open(addrBook, 'r', encoding='utf-8-sig') as addrFile:
        reader = csv.reader(addrFile)
        name = []
        value = []
        for row in reader:
            name.append(row[0])
            value.append(row[1])

    addrs = dict(zip(name, value))
    return addrs

3、如何读取正文文本?

# --------------------加载正文内容-------------------------

def getMailContent(content_path):
    if not os.path.exists(content_path):
        print("文件 content.txt 不存在")
        exit(0)

    with open(content_path, 'r') as contentFile:
        contentLines = contentFile.read().encode('gbk').decode('utf-8')
        if len(contentLines) < 1:
            print("no content in content.txt ")
            exit(0)
        mail_content = contentLines
    return mail_content

4、如何发送多个附件且只发送一次?

# --------------------添加附件-----------------------------------
def addAttch(attach_file):
    att = MIMEBase('application', 'octet-stream') # 将每一个附件转换成二进制流文件
    att.set_payload(open(attach_file, 'rb').read())
    # 此时的附件名称为****.xlsx,截取文件名
    att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attach_file.split("\\")[-1]))
    encoders.encode_base64(att)
    return att

5、如何发送给收件人?

# ---------------------发送邮件-----------------------
def mailSend():
    smtp = smtplib.SMTP()  # 新建smtp对象
    smtp.connect(sender_host)
    smtp.login(sender_user, sender_password)

    for root,dirs,files in os.walk(attach_path):
        msg = MIMEMultipart()
        for attach_file in files:
            # 挂接多个附件
            attach_file = root + "\\" + attach_file
            att = addAttch(attach_file)
            msg.attach(att)  # 附件
        # 挂接正文文本
        mail_content = getMailContent(content_path)
        msg.attach(MIMEText(mail_content,'plain','utf-8'))  # 正文  MIMEText(content,'plain','utf-8')
        # 设置邮件主题
        msg['Subject'] = Header(subject)  # 设置邮件主题
        # 设置发件人及收件人
        addrs = getAddrBook(addrBook)  #获取了姓名和邮箱地址
        msg['From'] = Header(sender_name+sender_user)  # 设置发件人名称
        msg['To'] =Header(";".join(addrs.values())) # 设置收件人名称
        to_addr = ','.join(addrs.values())
        smtp.sendmail(sender_user, to_addr.split(','), msg.as_string())  # smtp.sendmail(from_addr, to_addrs, msg)
        smtp.quit()

完整代码

**完整代码:**
# _*_coding: UTF-8_*_
# 开发时间:2022/3/10 16:30
# 文件名称:cs.py
# 开发人:鸿玥 世昕
# 开发工具:PyCharm


import pandas as pd
import csv
import smtplib
import os
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 服务器配置
sender_host = "smtp.qq.com:25"  #服务器地址及端口
sender_user = "xxxxxx@qq.com"
sender_password = "lyuwoewskniwdfhg" #授权码
sender_name="xxx"

# 附件所在文件夹
attach_path = r'E:\code\attachfile'
# 邮件地址通讯录地址
addrBook = r'E:\code\邮箱联系人表单.csv'
# 邮件正文地址
content_path =r'E:\code\content.txt'
# 邮件主题内容
subject ='2022报告'



def set_newexcel():
    # 读取数据
    data1 = pd.read_excel('E:/code/a.xlsx')
    data2 = pd.read_excel('E:/code/b.xlsx')

    # 提取两个数据公共的id
    id1 = data1.id.to_list()
    id2 = data2.id.to_list()
    common_id = set(id1).intersection(set(id2))
    # 产生新的数据
    new_data1 = data1[~data1.id.isin(common_id)]
    new_data2 = data2[~data2.id.isin(common_id)]
    # 保存新的数据                                    不显示索引值
    new_data1.to_excel('E:/code/attachfile/new_a.xlsx', index=False)
    new_data2.to_excel('E:/code/attachfile/new_b.xlsx', index=False)



# --------------根据输入的CSV文件,获取通讯录人名和相应的邮箱地址-------
def getAddrBook(addrBook):
    with open(addrBook, 'r', encoding='utf-8-sig') as addrFile:
        reader = csv.reader(addrFile)
        name = []
        value = []
        for row in reader:
            name.append(row[0])
            value.append(row[1])

    addrs = dict(zip(name, value))
    return addrs


# --------------------加载正文内容-------------------------

def getMailContent(content_path):
    if not os.path.exists(content_path):
        print("文件 content.txt 不存在")
        exit(0)

    with open(content_path, 'r') as contentFile:
        contentLines = contentFile.read().encode('gbk').decode('utf-8')
        if len(contentLines) < 1:
            print("no content in content.txt ")
            exit(0)
        mail_content = contentLines
    return mail_content


# --------------------添加附件-----------------------------------

def addAttch(attach_file):
    att = MIMEBase('application', 'octet-stream')  # 将每一个附件转换成二进制流文件
    att.set_payload(open(attach_file, 'rb').read())
    # 此时的附件名称为****.xlsx,截取文件名
    att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attach_file.split("\\")[-1]))
    encoders.encode_base64(att)
    return att


# ---------------------发送邮件-----------------------
def mailSend():
    smtp = smtplib.SMTP()  # 新建smtp对象
    smtp.connect(sender_host)
    smtp.login(sender_user, sender_password)

    for root,dirs,files in os.walk(attach_path):
        msg = MIMEMultipart()
        for attach_file in files:
            # 挂接多个附件
            attach_file = root + "\\" + attach_file
            att = addAttch(attach_file)
            msg.attach(att)  # 附件
        # 挂接正文文本
        mail_content = getMailContent(content_path)
        msg.attach(MIMEText(mail_content,'plain','utf-8'))  # 正文  MIMEText(content,'plain','utf-8')
        # 设置邮件主题
        msg['Subject'] = Header(subject)  # 设置邮件主题
        # 设置发件人及收件人
        addrs = getAddrBook(addrBook)  #获取了姓名和邮箱地址
        msg['From'] = Header(sender_name+sender_user)  # 设置发件人名称
        msg['To'] =Header(";".join(addrs.values())) # 设置收件人名称
        to_addr = ','.join(addrs.values())
        smtp.sendmail(sender_user, to_addr.split(','), msg.as_string())  # smtp.sendmail(from_addr, to_addrs, msg)
        smtp.quit()





if __name__ == '__main__':
    set_newexcel()
    mailSend()



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值