gpt4 book ai didi

python-2.7 - 是否可以使用python将已发送的电子邮件保存到已发送的项目文件夹中?

转载 作者:行者123 更新时间:2023-12-04 13:23:38 24 4
gpt4 key购买 nike

我想发送一封电子邮件,但发送的邮件是空的。如何发送电子邮件,然后将其副本放入“已发送”邮件文件夹。我能做什么?

最佳答案

是的,有可能。

基本上,您需要创建一个 MIME 电子邮件,然后通过 smptlib 将其发送,然后使用 imaplib 将其保存在“已发送”中。

The official imaplib documentation.

More detailed examples of using imaplib.

这是一个例子:

import time
import ssl
import imaplib
import smtplib
import email

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

class Mail:
def __init__(self):
# considering the same user and pass for smtp an imap
self.mail_user = 'youruser@yourdomain.com'
self.mail_pass = 'pass'
self.mail_host = 'mail.yourdomain'


def send_email(self, to, subject, body, path, attach):
message = MIMEMultipart()
message["From"] = self.mail_user
message["To"] = to
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))

with open(path + attach, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)

part.add_header(
"Content-Disposition",
"attachment; filename= \"" + attach + "\"",
)
message.attach(part)
text = message.as_string()

context = ssl.create_default_context()
with smtplib.SMTP_SSL(self.mail_host, 465, context=context) as server:
result = server.login(self.mail_user, self.mail_pass)
server.sendmail(self.mail_user, to, text)

imap = imaplib.IMAP4_SSL(self.mail_host, 993)
imap.login(self.mail_user, self.mail_pass)
imap.append('INBOX.Sent', '\\Seen', imaplib.Time2Internaldate(time.time()), text.encode('utf8'))
imap.logout()


if __name__ == '__main__':
m = Mail()
m.send_email('someone@somewhere.com', 'Hello', 'Its just a test!', 'c:\\', 'test.pdf')

关于python-2.7 - 是否可以使用python将已发送的电子邮件保存到已发送的项目文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44823746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com