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

1586010002-jmsa.png

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)

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

解决方案

This is the code that worked for me- to send an email with an attachment in 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值