gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:23:18 26 4
gpt4 key购买 nike

如何在使用 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()

最佳答案

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

关于python - 发送python邮件时添加excel文件附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25346001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com