2016-03-21 2 views
0

Я читаю почту из стандартного ввода с использованиемИспользование Python для изменения E-Mail (email.Message) и добавить вложение

message = mailbox.email.message_from_file(sys.stdin) 

и хочет добавить вложение текстового файла. Я пробовал следующее:

new_msg = email.mime.multipart.MIMEMultipart('related') 

old_msg = email.mime.message.MIMEMessage(message) 
new_msg.attach(old_msg) 

att_msg = email.mime.text.MIMEText("Textfile attachment") 
att_msg.add_header('Content-Disposition', 'attachment', filename= 'my_attachment.txt') 
new_msg.attach(att_msg) 

maildir.add(new_msg) 

, где maildir = mailbox.Maildir('~/mail').

Тем не менее, я получаю сообщение в ~/mail с двумя вложениями ForwardedMessage.eml и my_attachment.txt.

Моя цель состоит в том, чтобы иметь исходное сообщение (с теми же заголовками), но с прикрепленным текстовым файлом.

EDIT Позвольте привести пример. Первоначальное сообщение:

To: [email protected] 
From: User <[email protected]> 
Message-ID: <[email protected]> 
Date: Wed, 23 Mar 2016 15:40:18 +0100 
MIME-Version: 1.0 
Content-Type: text/plain; charset=utf-8; format=flowed 
Content-Transfer-Encoding: 7bit 

Testmessage 

С моим кодом:

Content-Type: multipart/related; boundary="===============7892775444970429949==" 
MIME-Version: 1.0 

--===============7892775444970429949== 
Content-Type: message/rfc822 
MIME-Version: 1.0 

To: [email protected] 
From: User <[email protected]> 
Message-ID: <[email protected]> 
Date: Wed, 23 Mar 2016 15:40:18 +0100 
MIME-Version: 1.0 
Content-Type: text/plain; charset=utf-8; format=flowed 
Content-Transfer-Encoding: 7bit 

Testmessage 

--===============7892775444970429949== 
Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 
Content-Disposition: attachment; filename="atach.txt" 

Textfile attachment 
--===============7892775444970429949==-- 

И это то, что Thunderbird дает мне (и то, что я хочу):

To: [email protected] 
From: User <[email protected]> 
Message-ID: <[email protected]> 
Date: Wed, 23 Mar 2016 15:40:18 +0100 
MIME-Version: 1.0 
Content-Type: multipart/mixed; boundary="------------010607020403070301060303" 

This is a multi-part message in MIME format. 
--------------010607020403070301060303 
Content-Type: text/plain; charset=utf-8; format=flowed 
Content-Transfer-Encoding: 7bit 

Testmessage 

--------------010607020403070301060303 
Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 
Content-Disposition: attachment; filename="atach.txt" 

Textfile attachment 
--------------010607020403070301060303-- 

ответ

0

Я просто попытался ваш код и он отлично работает, я обеспечу рабочее решение. Я думаю, что лучше импортировать необходимые классы модулей в качестве отдельных классов для использования в коде. Как показано здесь

import sys 
import mailbox 
import email 
from email.mime.multipart import MIMEMultipart 
from email.mime.message import MIMEMessage 
from email.mime.text import MIMEText 

message = mailbox.email.message_from_file(sys.stdin) 
maildir = mailbox.Maildir('./mail',create=True) 
new_msg = MIMEMultipart('related') 

old_msg = MIMEMessage(message) 
new_msg.attach(old_msg) 

att_msg = MIMEText("Textfile attachment") 
att_msg.add_header('Content-Disposition', 'attachment',filename='atach.txt') 
new_msg.attach(att_msg) 

maildir.add(new_msg) 

Я также передал дополнительное ключевое слово arg для создания почтового ящика, если оно не существует. create = True.

Эксплуатация вышеуказанного и проверка почты Дир дает мне следующее, я надеюсь, что это то, чего вы желаете.

Content-Type: multipart/related; boundary="===============2731426334901210480==" 
MIME-Version: 1.0 

--===============2731426334901210480== 
Content-Type: message/rfc822 
MIME-Version: 1.0 


Hello trial 2 

--===============2731426334901210480== 
Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 
Content-Disposition: attachment; filename="atach.txt" 

Textfile attachment 
--===============2731426334901210480==-- 
+0

Да, код дает мне сообщение как ваше. Тем не менее, как mutt, так и Thunderbird отображает сообщение с вложениями _two_: исходное сообщение и текстовый файл. – scus

Смежные вопросы