是否可以使用python将发送的电子邮件保存到已发送的项目文件夹中? [英] Is it possible to save the sent email into the sent items folder using python?

查看:335
本文介绍了是否可以使用python将发送的电子邮件保存到已发送的项目文件夹中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to sends an email but sent mail is empty. how to send an email, and then put a copy of it in the "Sent" mail folder. what can i do?

推荐答案

是的,有可能.

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

Basicaly you need to create an MIME email and then send it throug smptlib and than save it on Sent with imaplib.

官方 imaplib 文档.

更详细的 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将发送的电子邮件保存到已发送的项目文件夹中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆