繁体   English   中英

如何在Python中发送带有Excel文件(xlsx)附件的电子邮件

[英]how to send email with Excel file (xlsx)attachment in Python

我需要发一封带有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格式文件)

方法一:

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) 

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

方法二:

 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格式的文件

方法三:

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

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

试试这个代码来添加附件:

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

我试图发送一个 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM