Электронная почта с использованием 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 = "[email protected]"
you = "[email protected] "


# 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 = """\
<html> This is email</html>
"""

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 <module>
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». Этот файл похож на черновик моего электронного письма или что-то в этом роде. может кто-нибудь показать мне, как использовать это шоу и на самом деле электронная почта вместо черновика? Благодарность


person Super Saiyan    schedule 05.02.2014    source источник
comment
Вы уверены, что отправляете электронное письмо? Проверьте последнюю часть кода. :)   -  person NullDev    schedule 06.02.2014
comment
Было бы точнее использовать тип контента application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. application/vnd.ms-excel предназначен для .xls файлов (Excel 2003 и более ранние версии).   -  person John Y    schedule 06.02.2014


Ответы (1)


Чтобы отправить почту с локального хоста:

import smtplib

me = "[email protected]"
you = "[email protected]"

# insert your code here
msg = ...

s = smtplib.SMTP('localhost')
s.sendmail(me, [to], msg.as_string())
person unutbu    schedule 05.02.2014