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

时间:2017-06-29 11:22:24

标签: python-2.7 smtplib

我想发送电子邮件但发送的邮件是空的。 如何发送电子邮件,然后将其副本放在“已发送”邮件文件夹中。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

是的,有可能。

基本上,您需要创建一个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')