3

I am using exchangelib to connect to exchange and reply to emails. But while sending reply it doesn't support attachments.

As per this answer I have to " create a normal Message item that has a 'Re: some subject' title, contains the attachment, and quotes the original message, if that's needed."

but i am not sure how to "quote" the original message

I am using following code to reply:

from pathlib import Path from exchangelib import Message, Account, FileAttachment

account = Account(...)
item = ...
file_to_attach = Path('/file/to/attach.txt')
message = Message(
    account=account,
    subject="Re: " + item.subject,
    body="This is reply by code",
    cc_recipients=item.cc_recipients,
    to_recipients=[item.sender],
    in_reply_to=item.id,
    conversation_id=item.conversation_id,
)
with file_to_attach.open('rb') as f:
    content = f.read()
message.attach(FileAttachment(name=file_to_attach.name, content=content))
message.send_and_save()

It sends the email with attachment but it doesn't maintain text from original mail in reply and appears to be a new mail instead of a reply. also doesn't appear as conversation in gmail

I may be missing something small here. please suggest how to fix this

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
mry
  • 314
  • 2
  • 11

1 Answers1

3

After spending some more time looking for solution I found this answer in C# using which I was able to achieve the following solution:

attachment = FileAttachment(name=file_name, content=f.read())
reply = item.create_reply("Re: " + item.subject, "THIS IS REPLY FROM CODE" )
msg = reply.save(account.drafts)
msg.attach(attachment)
msg.send()

Hope this helps someone else looking for a solution to similar problem.

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
mry
  • 314
  • 2
  • 11
  • I've tried that but it failed because item.create_reply() returns a BulkCreateResult object I had to do: reply = item.create_reply("Re: " + item.subject, "THIS IS REPLY FROM CODE" ) bulk_created_results = reply.save(account.drafts) msg = account.inbox.get(id=bulk_created_results.id) msg.attach(attachment) msg.send() – eagle28 May 13 '21 at 14:41