Reputation: 1
I am using microsoft graph api's foward api to fowrad mail with CC and BCC, as I can't add CC and BCC address directly when we use fowrad api, I have created MIME format and added it over headers.
Now I am receiving two mails one for To address(with email thread) and another for To, Cc, and Bcc address (without email thread, but with last mesage).
Expected: mail triggering for To, CC and BCC addresses with email thread.
This is the function, where I construct MIME
def construct_mime_message(self, recipient, email_body, subject, cc_recipients=[], bcc_recipients=[], attachments=[]):
print(f"Constructing mime message: {recipient}, {cc_recipients}, {bcc_recipients}")
message = MIMEMultipart()
message["To"] = recipient
if cc_recipients:
cc_header = ", ".join(cc_recipients)
message["Cc"] = cc_header
if bcc_recipients:
message.add_header("Bcc", ", ".join(bcc_recipients))
message["Subject"] = subject
html_part = MIMEText(email_body, "html")
message.attach(html_part)
if attachments:
for attachment in attachments:
try:
part = MIMEBase('application', 'octet-stream')
part.set_payload(base64.b64decode(attachment["contentBytes"]))
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename="{attachment["name"]}"')
message.attach(part)
except Exception as e:
print(f"Error attaching file {attachment['name']}: {e}")
message_as_str = message.as_string()
return base64.b64encode(message_as_str.encode("utf-8")).decode()`
Below is the function to foward mail using fowrad api
def foward_email(self, target_email, external_id, access_token, email_body, subject, to_address, cc_addresses=None, bcc_addresses=None):
try:
messages_url = f"https://graph.microsoft.com/v1.0/users/{target_email}/mailFolders/inbox/messages?$filter=conversationId eq '{external_id}'"
headers = {"Authorization": f"Bearer {access_token}"}
messages_response = requests.get(messages_url, headers=headers).json()
message = messages_response["value"][0]
latest_email_id = message["id"]
mime_message = self.construct_mime_message(to_address, email_body, subject, cc_addresses, bcc_addresses)
forward_url = f"https://graph.microsoft.com/v1.0/users/{target_email}/messages/{latest_email_id}/forward"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "text/plain",
'Prefer': 'outlook.timezone="India Standard Time"'
}
fwd_response = requests.post(forward_url, headers=headers, data=mime_message)
if fwd_response.status_code == 202:
print("Mail sent successfully")
return True
else:
logging.error(f"Failed to send update email. Status code: {reply_response.status_code}")
logging.error(f"Response content: {reply_response.content}")
return False
except Exception as ex:
logging.error(f"An error occurred: {ex}")
return False
Result: > Mail triggred for CC and BCC without emial thread. > Receiving mail twice, one is for To address and other is for T0, Cc and BCC addresses
-Your response will be appreciated
Upvotes: 0
Views: 41