python附件发送到邮箱里_使用Python和Excel附件发送电子邮件

#!/usr/bin/env python3

import smtplib,email,email.encoders,email.mime.text,email.mime.base

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email import encoders

from email.message import Message

from email.mime.audio import MIMEAudio

from email.mime.base import MIMEBase

from email.mime.image import MIMEImage

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

msg = MIMEMultipart()

# me == my email address

# you == recipient's email address

me = "sender@email.com"

you = "reciever@email.com "

# Create message container - the correct MIME type is multipart/alternative.

msg = MIMEMultipart('mixed')

msg['Subject'] = "msg"

msg['From'] = me

msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).

text = "Hi\nThis is text-only"

html = """\

This is email

"""

part1 = MIMEText(text, 'plain')

part2 = MIMEText(html, 'html')

#attach an excel file:

fp = open('TestStatus.xlsx', 'rb')

file1=email.mime.base.MIMEBase('application','vnd.ms-excel')

file1.set_payload(fp.read())

fp.close()

email.encoders.encode_base64(file1)

file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')

# Attach parts into message container.

# According to RFC 2046, the last part of a multipart message, in this case

# the HTML message, is best and preferred.

msg.attach(part2)

msg.attach(part1)

msg.attach(file1)

composed = msg.as_string()

fp = open('msgtest.eml', 'w')

fp.write(composed)

# Credentials (if needed)

# The actual mail send

server = smtplib.SMTP('dc1smtp.com')

server.starttls()

server.sendmail(me, you, msg)

server.quit()

fp.close()

also when running it, I see this error message.

Traceback (most recent call last):

File "excel.py", line 57, in

server.sendmail(me, you, msg)

File "C:\Python33\lib\smtplib.py", line 775, in sendmail

(code, resp) = self.data(msg)

File "C:\Python33\lib\smtplib.py", line 516, in data

q = _quote_periods(msg)

File "C:\Python33\lib\smtplib.py", line 167, in _quote_periods

return re.sub(br'(?m)^\.', b'..', bindata)

File "C:\Python33\lib\re.py", line 170, in sub

return _compile(pattern, flags).sub(repl, string, count)

TypeError: expected string or buffer

我已经测试了这个代码,它正在工作。我唯一的问题是,当我运行它时,我没有收到我正在测试它的电子邮件。但当我运行这个代码时。它创建一个名为“msgtest.eml”的文件。这个文件就像我的电子邮件草稿什么的。

有人能告诉我如何使用这个节目,并成为一个真正的电子邮件,而不是草案?

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值