Python-回复电子邮件

Python-回复电子邮件,python,email,smtp,Python,Email,Smtp,我想用python和smtp回复特定的邮件。 我已经看过这些帖子: 但不幸的是,它只发送带有此'-----------转发消息-----的回复,而不是以正常方式回复 请帮忙 代码见附件 def reply_to_msg(self, original_msg, reply_body): # fetch msg self.login_imap(host="imap.gmail.com", port=993, username='username@gmail.com', passw

我想用python和smtp回复特定的邮件。 我已经看过这些帖子:

但不幸的是,它只发送带有此'-----------转发消息-----的回复,而不是以正常方式回复

请帮忙

代码见附件

def reply_to_msg(self, original_msg, reply_body):
    # fetch msg
    self.login_imap(host="imap.gmail.com", port=993, username='username@gmail.com', password="pass",
                  use_ssl=True)
    # Filter by subject because it is unique subject (uuid)
    # Get message ID
    mail_ids = self.receive_mail_ids(subject_filter=original_msg["Subject"])

    msg = MIMEMultipart("mixed")
    body = MIMEMultipart("alternative")

    text, _ = self.append_orig_text(reply_body, "", original_msg, True)

    body.attach(MIMEText(text, 'plain'))
    msg.attach(body)
    msg.attach(MIMEMessage(original_msg))

    msg["Message-ID"] = email.utils.make_msgid()
    msg['To'] = original_msg["From"]
    msg['Subject'] = "Re: " + original_msg["Subject"]
    msg['In-Reply-To'] = msg['References'] = mail_ids[-1]

    # send
    try:
        s = self.login_smtp(host="smtp.gmail.com", port=465, username='username@gmail.com', password="pass", use_ssl=True, use_auth=True)
        self.smtp.sendmail(original_msg['To'], [original_msg["From"]], msg.as_string())
    except Exception as error:
        raise EmailManagerError("sendmail: {}".format(error))

@staticmethod
def append_orig_text(text, html, orig, google=False):
    """
    Append each part of the orig message into 2 new variables
    (html and text) and return them. Also, remove any
    attachments. If google=True then the reply will be prefixed
    with ">". The last is not tested with html messages...
    """
    newhtml = ""
    newtext = ""

    for part in orig.walk():
        if (part.get('Content-Disposition')
                and part.get('Content-Disposition').startswith("attachment")):
            part.set_type("text/plain")
            part.set_payload("Attachment removed: %s (%s, %d bytes)"
                             % (part.get_filename(),
                                part.get_content_type(),
                                len(part.get_payload(decode=True))))
            del part["Content-Disposition"]
            del part["Content-Transfer-Encoding"]

        if part.get_content_type().startswith("text/plain"):
            newtext += "\n"
            newtext += part.get_payload(decode=False)
            if google:
                newtext = newtext.replace("\n", "\n> ")

        elif part.get_content_type().startswith("text/html"):
            newhtml += "\n"
            newhtml += part.get_payload(decode=True).decode("utf-8")
            if google:
                newhtml = newhtml.replace("\n", "\n> ")

    if newhtml == "":
        newhtml = newtext.replace('\n', '<br/>')

    return (text + '\n\n' + newtext, html + '<br/>' + newhtml)
def reply_to_msg(self、original_msg、reply_body):
#取味精
self.login\u imap(host=“imap.gmail.com”,端口=993,用户名=username@gmail.com,password=“pass”,
使用(ssl=True)
#按主题筛选,因为它是唯一主题(uuid)
#获取消息ID
邮件ID=self.receive邮件ID(主题过滤器=原始邮件[“主题”])
msg=MIMEMultipart(“混合”)
主体=MIMEMultipart(“备选方案”)
文本,self.append\u orig\u文本(回复正文,“,原始消息,True)
body.attach(MIMEText(纯文本)
附加信息(正文)
附加信息(信息原件)
msg[“Message ID”]=email.utils.make_msgid()
msg['To']=原始信息[“From”]
msg['Subject']=“Re:+原始信息[“Subject”]
msg['In-Reply-To']=msg['References']=mail_id[-1]
#发送
尝试:
s=self.login\u smtp(host=“smtp.gmail.com”,端口=465,用户名=username@gmail.com,password=“pass”,使用\u ssl=True,使用\u auth=True)
self.smtp.sendmail(原始邮件['To'],[原始邮件[“From”],.msg.as_string())
除异常作为错误外:
引发EmailManager错误(“sendmail:{}”。格式(错误))
@静力学方法
def append_orig_text(text,html,orig,google=False):
"""
将原始消息的每个部分追加到2个新变量中
(html和文本)并返回它们。此外,删除任何
附件。如果google=True,则答复将以前缀形式出现
使用“>”。最后一个不使用html消息测试。。。
"""
newhtml=“”
newtext=“”
对于原始行走()中的部分:
if(part.get('Content-Disposition'))
和part.get('Content-Disposition')。startswith(“附件”):
部分设置类型(“文本/普通”)
part.set_有效负载(“已删除附件:%s(%s,%d字节)”
%(part.get_filename(),
part.get_content_type(),
len(part.get_有效负载(decode=True)))
删除部分[“内容处置”]
del部分[“内容传输编码”]
如果part.get_content_type().startswith(“text/plain”):
newtext+=“\n”
newtext+=部分。获取_有效负载(解码=假)
如果谷歌:
newtext=newtext.replace(“\n”,“\n>”)
elif part.get_content_type().startswith(“text/html”):
newhtml+=“\n”
newhtml+=part.get_有效负载(decode=True).decode(“utf-8”)
如果谷歌:
newhtml=newhtml.replace(“\n”,“\n>”)
如果newhtml==“”:
newhtml=newtext.replace('\n','
')) 返回(text+'\n\n'+newtext,html+'
'+newhtml)
您希望发送何种回复?省略原始邮件应该是一个很简单的练习。回复方式与Gmail应用程序中的“回复”按钮相同。不是“转发消息”。