Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

smtplib - Is it possible to save the sent email into the sent items folder using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, its possible.

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

The official imaplib documentation.

More detailed examples of using imaplib.

Here is an example:

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 = '[email protected]'
        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('[email protected]', 'Hello', 'Its just a test!', 'c:\', 'test.pdf')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...