发送python电子邮件时添加excel文件附件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25346001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:05:29  来源:igfitidea点击:

add excel file attachment when sending python email

pythonemaildocumentattachment

提问by soccerplayer

How do i add a document attachment when sending an email with python ? i get the email to send (please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to send every 30 min, just have to change 5 to 1800)

使用python发送电子邮件时如何添加文档附件?我收到要发送的电子邮件(请忽略:我每 5 秒循环发送一次电子邮件,仅用于测试目的,我希望它每 30 分钟发送一次,只需将 5 更改为 1800)

here is my code so far. how do i attach a document from my computer?

到目前为止,这是我的代码。如何从我的计算机附加文档?

#!/usr/bin/python

import time
import smtplib

while True:
    TO = '[email protected]'
    SUBJECT = 'Python Email'
    TEXT = 'Here is the message'

    gmail_sender = '[email protected]'
    gmail_passwd = 'xxxx'

    server = smtplib.SMTP('smtp.gmail.com',587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gmail_sender, gmail_passwd)
    BODY = '\n'.join([
        'To: %s' % TO,
        'From: %s' % gmail_sender,
        'Subject:%s' % SUBJECT,
        '',
        TEXT

        ])

    try:
        server.sendmail(gmail_sender,[TO], BODY)
        print 'email sent'
    except:
        print 'error sending mail'

    time.sleep(5)

server.quit()

采纳答案by soccerplayer

This is the code that worked for me- to send an email with an attachment in python

这是对我有用的代码 - 在 python 中发送带有附件的电子邮件

#!/usr/bin/python
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders

def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = subject
    msg.attach(MIMEText(text))

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("WorkBook3.xlsx", "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')
    msg.attach(part)

    #context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
    #SSL connection only working on Python 3+
    smtp = smtplib.SMTP(server, port)
    if isTls:
        smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

回答by Andrew Johnson

To send an attachment create a MIMEMultipart object and add the attachment to that. Here is an example from the python email examples.

要发送附件,请创建一个 MIMEMultipart 对象并将附件添加到该对象中。这是 python电子邮件示例中的一个示例

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

回答by TonyRyan

Here is just a slight tweak on SoccerPlayer's post above that got me 99% of the way there. I found a snippet Herethat got me the rest of the way. No credit is due to me. Just posting in case it helps the next person.

这里只是对上面 SoccerPlayer 的帖子稍作调整,让我达到了 99%。我在这里找到了一个片段,让我完成了剩下的工作。没有信用是由于我。只是张贴以防它帮助下一个人。

file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()

回答by C. Tim

I found an easy way to do it using what Corey Shafer explains in this videoon sending emails with python.

我找到了一种简单的方法来使用 Corey Shafer 在这个视频中解释的使用 python 发送电子邮件。

import smtplib
from email.message import EmailMessage

SENDER_EMAIL = "[email protected]"
APP_PASSWORD = "xxxxxxx"

def send_mail_with_excel(recipient_email, subject, content, excel_file):
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = SENDER_EMAIL
    msg['To'] = recipient_email
    msg.set_content(content)

    with open(excel_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="xlsx", filename=excel_file)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(SENDER_EMAIL, APP_PASSWORD)
        smtp.send_message(msg)