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

问题描述 投票:0回答:7

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

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

#!/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()
python email document attachment
7个回答
67
投票

这是对我有用的代码 - 在 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()

15
投票

我找到了一种简单的方法,使用 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)

10
投票

这只是对上面 SoccerPlayer 的帖子的一个小小的调整,这让我完成了 99% 的工作。我找到了一个片段Here,它帮助我完成了剩下的事情。没有任何功劳归于我。只是发帖以防对下一个人有帮助。

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()

2
投票

使用python 3,您可以使用MIMEApplication

import os, smtplib, traceback
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def sendMail(sender,
             subject,
             recipient,
             username,
             password,
             message=None,
             xlsx_files=None):

    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = sender
    if type(recipient) == list:
        msg["To"] = ", ".join(recipient)
    else:
        msg["To"] = recipient
    message_text = MIMEText(message, 'html')
    msg.attach(message_text)

    if xlsx_files:
        for f in xlsx_files:
            attachment = open(f, 'rb')
            file_name = os.path.basename(f)
            part = MIMEApplication(attachment.read(), _subtype='xlsx')
            part.add_header('Content-Disposition', 'attachment', filename=file_name)
            msg.attach(part)

    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(username, password)
        server.sendmail(sender, recipient, msg.as_string())
        server.close()
    except Exception as e:
        error = traceback.format_exc()
        print(error)
        print(e)

注意* 在这个例子中我只是使用了

print(error)
。通常,我会将错误发送至
logging.critical(error)


1
投票

要发送附件,请创建一个 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()

0
投票

您也可以使用Red Mail很好地完成此任务:

from redmail import EmailSender

from pathlib import Path
import pandas as pd

gmail = EmailSender(
    host='smtp.gmail.com',
    port=465,
    user_name="[email protected]",
    password="<YOUR PASSWORD>"
)

gmail.send(
    subject="Python Email",
    receivers=["[email protected]"],
    text="Here is the message",
    attachments={
        # From path on disk
        "my_file.xlsx": Path("path/to/file.xlsx"),
        # Or from Pandas dataframe
        "my_frame.xlsx": pd.DataFrame({"a": [1,2,3]})
    }
)

如果您希望以这种方式附加 Excel 文件,也可以传递字节。

安装红邮件:

pip install redmail

Red Mail 是一个功能齐全的开源电子邮件库。它经过充分测试并有详细记录。文档可以在这里找到:https://red-mail.readthedocs.io/en/latest/


0
投票

请参考此链接。 https://techexpert.tips/python/python-send-email-using-office-365/

我用过,运行顺利。

© www.soinside.com 2019 - 2024. All rights reserved.