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

时间:2014-08-17 03:10:10

标签: python email document attachment

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

这是我的代码到目前为止。如何从我的电脑附加文件?

#!/usr/bin/python

import time
import smtplib

while True:
    TO = 'xxxx@gmail.com'
    SUBJECT = 'Python Email'
    TEXT = 'Here is the message'

    gmail_sender = 'xxxx@gmail.com'
    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()

4 个答案:

答案 0 :(得分:31)

这是为我工作的代码 - 在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()

答案 1 :(得分:3)

我发现使用Corey Shafer在this video中解释的使用python发送电子邮件的简单方法。

import smtplib
from email.message import EmailMessage

SENDER_EMAIL = "sender_email@gmail.com"
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)

答案 2 :(得分:1)

这里只是对SoccerPlayer帖子的一个细微调整,使我有99%的了解。我找到了一段Here,可以帮助我完成其余所有工作。没有信用归我所有。只是发布以防万一,可以帮助下一个人。

(gdb) run
Starting program: /home/ubuntu/ParaView-5.6.0-RC2-Qt5-MPI-Linux-64bit/bin/paraview 
process 10177 is executing new program: /home/ubuntu/ParaView-5.6.0-RC2-Qt5-MPI-Linux-64bit/lib/paraview
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-    gnu/libthread_db.so.1".
[New Thread 0x7fffcac8c700 (LWP 10205)]
[New Thread 0x7fffbd98e700 (LWP 10214)]
[New Thread 0x7fffbd18d700 (LWP 10215)]
[New Thread 0x7fffbc98c700 (LWP 10216)]
[New Thread 0x7fffaffff700 (LWP 10217)]

Thread 1 "paraview" received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
51  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) 

答案 3 :(得分:0)

要发送附件,请创建MIMEMultipart对象并将附件添加到该对象。以下是python email examples的一个示例。

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