Python 2.7 是否可以使用python将发送的电子邮件保存到sent items文件夹中?
我想发送电子邮件,但发送的邮件是空的。 如何发送电子邮件,然后将其副本放入“已发送”邮件文件夹。 我能做什么?是的,这是可能的 基本上,您需要创建一封MIME电子邮件,然后通过smptlib发送,然后将其保存在使用imaplib发送的邮件上 以下是一个例子:Python 2.7 是否可以使用python将发送的电子邮件保存到sent items文件夹中?,python-2.7,smtplib,Python 2.7,Smtplib,我想发送电子邮件,但发送的邮件是空的。 如何发送电子邮件,然后将其副本放入“已发送”邮件文件夹。 我能做什么?是的,这是可能的 基本上,您需要创建一封MIME电子邮件,然后通过smptlib发送,然后将其保存在使用imaplib发送的邮件上 以下是一个例子: import time import ssl import imaplib import smtplib import email from email import encoders from email.mime.base imp
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')
@如果你知道这个模块可以工作,你真的应该把它作为一个答案添加进去。@code\u byter:我不知道,我是新来的。谢谢。使用pdf(仅限)附件,是否可以使用“pdf”、“pdf”而不是“应用程序”、“八位字节流”?