Reputation: 55
So I am sending my email using sendgrid personalization something like this:
message = {
"personalizations": context["personalizations"],
"from": {"email": context["sender_email"]},
"subject": context["subject"],
"content": [{"type": MimeType.html, "value": context["body"]}],
"reply_to": {"email": context["reply_to"]}
}
sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))
sg.send(message)
Here context["personalization"] is an object as below:
{
"to": [{"email": applicant.email}],
"custom_args": {
"email_id": str(correspondance.id),
"env": settings.ENVIRONMENT
}
}
Sending and receiving the emails work fine. The problem is that I can't send an email as a reply to some email. Like a user sends me an email which I receive through sendgrid's inbound parse. Now I want to reply to the email I received.
A solution I found on the internet was that I have to add an 'in_reply_to' ID which I receive as Message_ID in inbound parse but that didn't work. I did something like this:
message = {
"personalizations": context["personalizations"],
"from": {"email": context["sender_email"]},
"subject": context["subject"],
"content": [{"type": MimeType.html, "value": context["body"]}],
"reply_to": {"email": context["reply_to"]},
"in_reply_to": message_id
}
sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))
sg.send(message)
Here the message_id is Message_ID I received in the inbound email's json.
Upvotes: 2
Views: 2702
Reputation: 173
What have worked best for me is setting the References header to an outbound mail to instruct email clients to create a thread.
Writers use References to indicate that a message has a parent. The last identifier in References identifies the parent. So the References header is a space
separated list of message IDs wrapped by <> in the following format:
"<MESSAGE_ID>"
You should check wether SendGrid already wraps the message you got from your inbound parse endpoint and then append it to the references string.
import sendgrid
import os
from sendgrid.helpers.mail import Mail, Email, To, Content
previously_received_mail_id = "<[email protected]>"
references = "" + previously_received_mail_id # empty in your case as its the first reply
sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("[email protected]") # Change to your verified sender
to_email = To("[email protected]") # Change to your recipient
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, to_email, subject, content)
mail.personalizations[0].add_header(Header("References",references))
# Get a JSON-ready representation of the Mail object
mail_json = mail.get()
# Send an HTTP POST request to /mail/send
response = sg.client.mail.send.post(request_body=mail_json)
print(response.status_code)
print(response.headers)
Upvotes: 1