Not able get email threads for CC and BCC addresses using Microsoft graph api: forward api

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}”)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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()`
</code>
<code> 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()` </code>
    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”]

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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`
</code>
<code> 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` </code>
        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

New contributor

Monisha Pattada is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật