我正在尝试使用Gmail API发送电子邮件回复。我写了以下代码,它不回复电子邮件,而是作为新邮件发送。
def create_message_with_attachment(
sender, to,cc, subject, message_text, file):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
message['cc'] = cc
msg = MIMEText(message_text)
message.attach(msg)
content_type, encoding = mimetypes.guess_type(file)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(file, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(file, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(file, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(file, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
encoders.encode_base64(msg)
encoded_message = urlsafe_b64encode(message.as_bytes())
raw_msg= {'raw': encoded_message.decode()}
raw_msg['threadId']= '16a7c412848d632d'
return raw_msg
已发送的电子邮件显示在我的邮箱中的线程下方,但对于收件人,它以新邮件的形式发送,而不是他之前发送的邮件的下方。