簡體   English   中英

如何使用 Python 轉發電子郵件

[英]How to forward email using Python

首先,讓我說,我已經知道在使用 python smtplib 轉發電子郵件時已經問過這個問題了。

我發布與該問題如此密切相關的內容的原因是我嘗試使用該問題的答案,我嘗試過更改內容,我已經搜索了谷歌並無情地玩弄了大約 5 個小時,我願意花更多的時間在這上面

- 我只是想你們中的一個人可能有答案:)

我的問題如下,我試圖將一封電子郵件從我的 gmail 轉發到另一個 gmail,並且在運行盡可能多的 python 腳本來嘗試這個簡單的任務時,我仍然無法弄清楚。

這是我正在運行的代碼(這是我以其他形式發布的內容的修改版本):

import smtplib, imaplib, email, string

imap_host = "imap.gmail.com"
imap_port = 993
smtp_host = "smtp.gmail.com"
smtp_port = 587
user = "John.Michael.Dorian.4"
passwd = "mypassword"
msgid = 1
from_addr = "John.Michael.Dorian.4@gmail.com"
to_addr = "myotheremail@gmail.com"


# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host, imap_port)
client.login(user, passwd)
client.select()
typ, data = client.search(None, 'ALL')
for mail in data[0].split():
    typ, data = client.fetch(msgid, "(RFC822)")
    email_data = data[0][1]
client.close()
client.logout()


# create a Message instance from the email data
message = email.message_from_string(email_data)

# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
print message.as_string()

# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.set_debuglevel(1)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string()) 
smtp.quit()

從 SMTP 調試返回說一切正常,我知道它正在發送,因為我嘗試更換

smtp.sendmail(from_addr, to_addr, message.as_string())

smtp.sendmail(from_addr, to_addr, 'test')

它工作得很好。 它打印 message.as_string() 很好,我不知道如何讓它轉發電子郵件!

它不必與 SMTP 或 IMAP 或任何此類代碼(盡管如果是這樣會很好)但我真的很想弄清楚如何做到這一點。

我知道這是可能的,因為我昨天設法做到了,而我正在使用的計算機(當然是運行 Windows)崩潰了,文件也不見了。

對於那些想知道為什么我不只是將 google 設置為自動轉發所有內容的人,這是因為我想要一個最終會移動大量郵件的腳本,一次。

謝謝大家!

很有可能,原始電子郵件的 Received: 標題導致 gmail 丟棄該郵件。 在轉發之前嘗試刪除所有這些。

如果這不能解決問題,請打印出標題並對其進行編碼以刪除所有通常不會出現在新編寫的消息中的標題。

然而,為什么要這樣前進呢? 從一個 IMAP 帳戶中提取並將其直接推送到另一個 IMAP 帳戶會更容易。

事實上,您可以使用 Mozilla Thunderbird 添加兩個帳戶,然后將消息從一個拖放到另一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM