这里写自定义目录标题

  • 用python发带附件的邮件
  • 配置文件及附件
  • 从Foxmail获取编写邮件正文


用python发带附件的邮件

主要功能:

  1. 读取excel文件,文件最后一列为收件人姓名.
  2. 根据收件人姓名转拼音生成邮件地址.
  3. 直接读取目录下的附件
  4. 解决了outlook邮件名乱码问题在这里插入代码片
  5. 从文件中获取html做为邮件正文
# -*- coding: utf-8 -*-
import openpyxl
import os
import smtplib
from email.utils import formataddr
from xpinyin import Pinyin
import time
from email.mime.text import MIMEText    
from email.mime.multipart import MIMEMultipart  
import configparser
from email import encoders
from email.mime.application import MIMEApplication
from email.header import  make_header



#读取配置文件,获取邮件信息
cf = configparser.ConfigParser()
cf.read("data\\config.txt",encoding="utf-8-sig")

###汉字转拼音
def Topinyin(name):
    pin = Pinyin()
    pinyin = pin.get_pinyin(name,"")
    return pinyin

###写日志
def writelog(log):
    with open('data\\logaddattached.txt','a',encoding='UTF-8-sig') as f:
        t=time.localtime()
        y=str(t.tm_year)
        m=str(t.tm_mon)
        d=str(t.tm_mday)
        hour=str(t.tm_hour)
        min=str(t.tm_min)
        sec=str(t.tm_sec)
        tt=(y+'/'+m+'/'+d+' '+hour+':'+min+':'+sec)
        f.writelines (tt+'\t'+log+'\n')
        f.close

###读取附件
def getAttach():
    files=[]
    for root,dirs,files1 in os.walk(r"data\Attachment"):
        for f1 in files1:
            files.append(f1)
    return files


###获取邮件内容
def getmail():
    with open('data\\mailinfo.txt','r',encoding='UTF-8-sig') as mail:
        return(mail.read())	
        mail.close
         
###发邮件
def send_email(mailaddr,name,fistname,mailinfo):

    
###邮箱配置---测试
    # mailaddr='5829@qq.com'
    # sender = 'XXXXXX@126.com'  # 发件人邮箱账号
    # passwd = '123@abcdefghijk' #发什人帐号密码
    # mailserver = "smtp.126.com"  #邮件服务器地址
    # port = '25'  #服务器端口
    # sub = '邮件主题'  #邮件标题
    # cc = 'CC@126.com'
     

####邮箱配置--正式
    
    sender = cf.get("Email-user", "sender")                #发件人
    passwd = cf.get("Email-user", "passwd")                #发件人密码
    mailserver = cf.get("Mail-server", "mailserver")       #邮件服务器地址
    port = cf.get("Mail-server", "port")                   #邮件服务器端口号
    sub = cf.get("Email-user", "sub")                      #邮件标题
    print('邮件主题:',sub)
    cc = cf.get("Email-user", "cc")                        #抄送人

    try:
        msg = MIMEMultipart('related')
        msg['To'] = formataddr([name, mailaddr])  # 收件人邮箱昵称、收件人邮箱账号
        msg['From'] = formataddr(["王宝伟",sender])  # 发件人邮箱昵称、发件人邮箱账号
        msg['Cc'] = formataddr(['',cc])
        msg['Subject'] = sub
        Mailto=[]
        Mailto.append(mailaddr)
        ####添加抄送人
        # Mailto.append(cc)

        ###添加附件, 使用make_header函数解决outlook附件乱码问题        
        filelist = getAttach()         
        for fn in filelist:
            filename='data\Attachment\\'+fn
            # print('filepath:',filename)
            # print('filename:',fn)
            with open(filename,'rb') as f:
                attachfile = MIMEApplication(f.read())
                attachfile.add_header('Content-Disposition', 'attachment',filename = '%s' % make_header([(fn,'utf-8')]).encode('utf-8'))
                msg.attach(attachfile)
                           
        writelog("发邮件给:" + str(Mailto))
            
        ###构造邮件正文
        body = """<span style="font-size: 14px;"><font face="微软雅黑">"""+fistname+"你好: <br>"
        body += mailinfo
        # writelog(body)
        ###邮件正文使用utf-8编码解决outlook邮件正文乱码问题
        text = MIMEText(body, 'html', 'utf-8')
        msg.attach(text)
        writelog ('构造邮件成功!')        
        #####发送邮件
        server =smtplib.SMTP()
        server.connect(mailserver)
        print ('连接服务器成功')
        server = smtplib.SMTP(mailserver, port)  # 发件人邮箱中的SMTP服务器,端口是25
        server.login(sender, passwd)  # 发件人邮箱账号、邮箱密码
        server.sendmail(sender,Mailto, msg.as_string())  # 发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()             
        writelog('发送邮件成功')
        print('发送邮件成功')
        
    except Exception as e:
        print(e)
#        writelog(e)
       
##读取excel文件发送邮件
def read_excel():
    mailf=cf.get("Email-receive", "mailFile")
    #获取要发送的邮件内容
    mailinfo=getmail()
    #打开表格发送邮件
    wb = openpyxl.load_workbook('data\\'+mailf)
    ws = wb.active  # 当前活跃的表单
    writelog ("********************************************************")
        
    for row in range (263,ws.max_row+1):
    # for row in range (1,3):
        writelog ("****当前是第:" + str (row) +"条数据*********")
        isEmailaddr = cf.get("Email-receive", "isEmailaddr")   
#        print(isEmailaddr)
        if isEmailaddr == 'F' :
            name=ws.cell(row,1).value
            fistname=repr(name)[1]+'工'
            mailsuffix=cf.get("Email-receive", "mailsuffix")
            mailaddr=Topinyin(name)+'@'+mailsuffix
        else:
            fistname="领导"
            mailaddr=ws.cell(row,1).value
            name=" "

        writelog("姓名:"+name)
        writelog("邮件:"+mailaddr)           
        writelog("姓氏:"+fistname)
        print("姓名:"+name)

        send_email(mailaddr,name,fistname,mailinfo)

        time.sleep(20)
        writelog("延时30秒")
        print("-----------------延时30秒----------------")

#        调用发邮件模块
read_excel()

os.system("pause")

配置文件及附件

python操作foxmail日历_python操作foxmail日历


配置文件

[Email-user]

sender = w123i@126.com

passwd = 123@456

cc = 123i@hqq.com

sub =产品推荐

[Mail-server]
mailserver = 1236.com
port = 25

[Email-receive]
mailFile=example.xlsx
isEmailaddr=F
mailsuffix=123.com
邮件正文:

```php
<style class="fox_global_style">div.fox_html_content { line-height: 1.5; }div.fox_html_content { font-size: 12pt; font-family: 微软雅黑; color: rgb(0, 0, 0); line-height: 1.5; }</style> <div>您好</div><div><span id="_FoxCURSOR"></span>在Foxmail编写一段文字, 然后查看HTML源码,复制到文本文件中, 做为邮件正文.</div><div><br></div><div><br></div> <div><br></div>

从Foxmail获取编写邮件正文

python操作foxmail日历_python操作foxmail日历_02


python操作foxmail日历_html_03