如何使用Python中的Excel文件(xlsx)附件发送电子邮件

时间:2017-08-14 06:03:54

标签: python excel email

我需要发送一封包含Excel附件的电子邮件。    我的代码如下,可以发送电子邮件,    但是当我收到电子邮件时,附件文件不是Excel文件~~    似乎我附加了错误的格式~~~

我添加了不同的电子邮件地址来接收此电子邮件,    但他们都收到了未知的格式文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import datetime
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.mime.base import MIMEBase
from email import encoders

mail_host = "mysever"  # 设置服务器
mail_user = "me"    # 用户名
mail_pass = "me123"   # 口令

EMAILHOME = u'F:\Workfiles\weekreport\\forupdate'
sender = 'me@gmail.com'
receivers = ['aaaaaa@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱


def getReceiverlist(filename):
    lif = open(filename)
    li = lif.readlines()
    lif.close()
    for x in range(len(li)):
        li[x] = li[x].strip(os.linesep)
    while '' in li:
        li.remove('')
    return li


def aisendmail():
    ret = True
    try:
        message = MIMEMultipart()
        message['From'] = Header("myname", 'utf-8')
        message['To'] = Header("youname", 'utf-8')
        message.attach(MIMEText('weekreport', 'plain', 'utf-8'))  # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码

        subject = 'myname-weekreport'
        message['Subject'] = Header(subject, 'utf-8')

        att1 = MIMEBase('application', "octet-stream")
        att1.set_payload(open(u"F:\Workfiles\weekreport\\forupdate\myname_weekreport_20170821.xlsx",'rb').read())
        encoders.encode_base64(att1)
        att1.add_header('Content-Disposition', 'attachment; filename="myname-weekreport"')
        message.attach(att1)

        if os.path.exists(EMAILHOME + r'\receivers.txt'):
            receiverslist = getReceiverlist(EMAILHOME + r'\receivers.txt')
            print("receicerlist include:", receiverslist)
            if len(receiverslist) == 0:
                print"no receiver!!!"
                receiverslist = receivers
        else:
            receiverslist = receivers

        server = smtplib.SMTP()
        server.connect(mail_host, 25)  # 发件人邮箱中的SMTP服务器,端口是25
        server.login(mail_user, mail_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(sender, receiverslist, message.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except smtplib.SMTPException:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False
        ret = False
    return ret

result = aisendmail()
if result:
    print "邮件发送成功"
else:
    print "Error: 无法发送邮件"

我按照不同的方式添加excel附件如下:但它们都失败了(这意味着它无法接收excel格式文件)

方法1:

att1 = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
att1.set_payload(open(file, 'rb').read())
encoders.encode_base64(att1)
att1.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 
msg.attach(att1) 

结果:     收到一个未知的格式文件

方法2:

 with open(u"F:\Workfiles\周报\\forupdate\xxx_周报_20170821.xlsx", "rb") as fil:
        part = MIMEApplication(
            fil.read(),
            Name=basename(u"F:\Workfiles\周报\\forupdate\xxx_周报_20170821.xlsx")
        )
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(u"F:\Workfiles\周报\\forupdate\xxx_周报_20170821.xlsx")
        message.attach(part)

结果:   收到了bin格式文件

方法3:

att1 = MIMEApplication(open('foo.xlsx','rb').read()) 
att1.add_header('Content-Disposition', 'attachment', filename="foo.xlsx") 
msg.attach(att1)

结果:     收到未知格式文件

2 个答案:

答案 0 :(得分:0)

尝试使用此代码添加附件:

with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
            msg.attach(part)

答案 1 :(得分:0)

我试图发送以HTML格式设置的正文,并添加一个excel文件作为附件-这使我花了很长时间才弄清楚,所以最好以为我应该分享我的解决方案!

from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'This is my subject line'
msg['To'] = xxxxx@xmail.com
msg['From'] = yyyyy@ymail.com

msg.add_alternative(f"""\
        <!DOCTYPE html>
            <html>
                <body>
                    <h3>This is my message!</h3>
                </body>
            </html>""",
    subtype='html')

with open('MyExcelFile.xlsx', 'rb') as fh:
    attachment = fh.read()
    msg.add_related(attachment, maintype='application', subtype='xlsx', filename='MyExcelFile.xlsx')

with smtplib.SMTP_SSL(host='smtp.gmail.com', port=465) as smtp:
    smtp.login('obviouslyfake@gmail.com', 'WhoDoYouThinkIAm')
    smtp.send_message(msg)
相关问题
最新问题