I am using SendGrid for Python. I want to CC some people in an email. It seems like they may no longer support CC'ing on emails, though I'm not positive if that's true? But surely there is a work around to it somehow, but I am surprised I can't find much support on this.
Here is my basic code:
sg = sendgrid.SendGridAPIClient(apikey='*****')
from_email = Email(sender_address, sender_name)
to_email = Email(email_address)
subject = subject
content = Content("text/plain", email_message)
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
How can I modify this so it will CC someone on an email?
Using the SendGrid's Personalization() or Email() class did not work for me. This is how I got it to work:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Cc
# using a list of tuples for emails
# e.g. [('email1#example.com', 'email1#example.com'),('email2#example.com', 'email2#example.com')]
to_emails = []
for r in recipients:
to_emails.append((r, r))
# note the Cc class
cc_emails = []
for c in cc:
cc_emails.append(Cc(c, c))
message = Mail(
from_email=from_email,
to_emails=to_emails,
subject='My Subject',
html_content=f'<div>My HTML Email...</div>'
)
if cc_emails:
message.add_cc(cc_emails)
try:
sg = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))
sg.send(message)
except Exception as e:
print(f'{e}')
Hopefully this helps someone.
I resolved it. Santiago's answer got me mostly there, but here is what I needed to do:
sg = sendgrid.SendGridAPIClient(apikey='****')
from_email = Email(sender_address, sender_name)
to_email = Email(to_email)
cc_email = Email(cc_email)
p = Personalization()
p.add_to(to_email)
p.add_cc(cc_email)
subject = subject
content = Content("text/plain", email_message)
mail = Mail(from_email, subject, to_email, content)
mail.add_personalization(p)
response = sg.client.mail.send.post(request_body=mail.get())
If you don't include the p.add_to(to_email) it rejects it because there is no "to email" in the personalization object. Also, if you don't include the "to_email" inside the mail object it rejects it because it is looking for that argument, so you have to be a bit redundant and define it twice.
I've been looking at the code: https://github.com/sendgrid/sendgrid-python/blob/master/examples/mail/mail.py
And it looks like you can do that by adding a personalization to the mail, for example:
cc_email = Email(cc_address)
p = Personalization()
p.add_cc(cc_email)
mail.add_personalization(p)
Based on the answers here you can CC to email if you add another email to 'to_email'.
If you want to cc multiple user then in djanogo using sendgrid you need to import the below line
the function that will be used to send the mail
and finally how you ned to send the data paramters to the above function so that it can CC the person
email = send_sandgridmail(sender=sender,receiver=receivers,subject=subject,content=message,reply_to=sender,cc=[admin_mail_account_mail,"rawatanup918#gmail.com"],attachment=None)
i hope this'll help.simplified from #anurag image script
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import To,Mail,ReplyTo,Email,Cc
def send_sandgridmail (sender, receiver, subject, content, reply_to=None, cc=[], attachment=None) :
# content = convert_safe_text(content)
# to email = To(receiver)
message = Mail(
from_email=str(sender),
to_emails=receiver,
subject= str(subject),
html_content = content)
if reply_to:
message.reply_to= ReplyTo(reply_to)
if attachment:
message.add_attachment (attachment)
if len(cc):
cc_mail = []
for cc_person in cc:
cc_mail.append(Cc(cc_person, cc_person))
message.add_cc (cc_mail)
try:
SENDGRID_API_KEY = 'your sendgrid api key'
sg= SendGridAPIClient (SENDGRID_API_KEY)
response= sg.send(message)
print (response.status_code)
# print (response.body)
# print (response.headers)
except Exception as e:
print(e)
return response
Related
Full disclosure: I am very new to coding and I really don't know what I'm doing. Currently trying to send multiple transactional emails using SendinBlue SMTP API based on the one I pick. I have already made the templates on SendinBlue, but how do I call a specific template?
My code
from __future__ import print_function
import sib_api_v3_sdk
import smtplib
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
from email.mime.text import MIMEText
from flask import request, render_template
from sql_helper import *
# Configuration of API key authorization:
api_config = sib_api_v3_sdk.Configuration()
api_config.api_key['api-key'] = 'api_key'
#If Partnership Account:
#api_config = sib_api_v3_sdk.Configuration()
#api_config.api_key['partner-key'] = 'API_Key'
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(api_config))
subject = "My Subject"
html_content = "<html><body><h1>This is my first transactional email </h1></body></html>"
sender = {"name":"company name","email":"admin#company.com"}
to = [{"email":"example#example.com","name":"Jane Doe"}]
# cc = [{"email":"example2#example2.com","name":"Janice Doe"}]
# bcc = [{"name":"John Doe","email":"example#example.com"}]
reply_to = {"email":"admin#company.com","name":"John Doe"}
headers = {"Some-Custom-Name":"unique-id-1234"}
params = {"parameter":"My param value","subject":"New Subject"}
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to, reply_to=reply_to, headers=headers, html_content=html_content, sender=sender, subject=subject)
def send_email(template, recipient, custom_message = None):
if template == "approve":
template_id = 1
elif template == "deny":
template_id = 2
elif template == "skip":
template_id = 3
try:
#send transactional email
api_response = api_instance.send_transac_email(send_smtp_email)
pprint(api_response)
except ApiException as e:
print("Exception when calling SMTPApi -> send_transac_email: %s\n" % e)
Any help would be appreciated.
I really am not quite sure what I'm doing, so anything would help. I'm sorry if the code is bad, I'm just starting out.
I'm trying to send a bulk email using Sendgrid Dynamic Templates in Django and getting this error: The personalizations field is required and must have at least one personalization.
Using sendgrid 6.9.7
Does anyone see where I might be going wrong:
from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To
def send_mass_email():
to_emails = [
To(email='email1#gmail.com',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 1',
}),
To(email='email2#gmail.com',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 2',
}),
]
msg = Mail(
from_email='notifications#mysite.com>',
)
msg.to_emails = to_emails
msg.is_multiple = True
msg.template_id = "d-template_id"
try:
sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sendgrid_client.send(msg)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e)
print(e.body)
return
The output is
HTTP Error 400: Bad Request
b'{"errors":[{"message":"The personalizations field is required and must have at least one personalization.","field":"personalizations","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"}]}'
The Mail class does some stuff during initialization with the initial values (it sets private internal values based on to_emails), so you need to pass to_emails and is_multiple in the initializer and not later:
from django.conf import settings
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To
def send_mass_email():
to_emails = [
To(email='email1#gmail.com',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 1',
}),
To(email='email2#gmail.com',
dynamic_template_data={
"thing_i_want_personalized": 'hello email 2',
}),
]
msg = Mail(
from_email='notifications#mysite.com>',
to_emails = to_emails,
is_multiple = True
)
msg.template_id = "d-template_id"
try:
sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sendgrid_client.send(msg)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e)
print(e.body)
return
In python 3 and sendgrid I need to send BCC type emails and use a dynamic template, which I built here
In the dynamic template I put a blank space to receive data that I will send. I created the variable {{lista}} in the blank space. It looked like this in the HTML of the whitespace template:
<div style="font-family: inherit; text-align: inherit">{{sentences}}</div>
My python code looked like this:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Attachment, Mail
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException, Personalization, Bcc
import os
API_KEY = "real id"
lista = ["Sentence 1 <br>", "Sentence 2 <br>"]
lista = {"sentences": lista}
recips = ['email1#gmail.com', 'email2#gmail.com', 'email2#gmail.com']
to_emails = [
To(email= 'one_valid_email#gmail.com',
dynamic_template_data = lista)]
personalization = Personalization()
personalization.add_to(To('one_valid_email#gmail.com'))
for bcc_addr in recips:
personalization.add_bcc(Bcc(bcc_addr))
message = Mail(
from_email=('emailsender#gmail.com'),
subject="email subject",
to_emails=to_emails,
is_multiple=True)
message.add_personalization(personalization)
message.template_id = 'real id'
try:
sendgrid_client = SendGridAPIClient(api_sendgrid)
response = sendgrid_client.send(message)
print(response.status_code)
#print(response.body)
#print(response.headers)
except Exception as e:
print(e.message)
return
The email is sent, but with empty templates, without "list" data
Please, does anyone know what could be wrong?
Here is the image of my template, the place I created the blank to receive the data:
And here the HTML code of the place, Edit Module HTML:
That is because you are trying to call the method add_personalization on the to_emails object, which is a list that you defined a few lines above:
to_emails = [To(email= 'one_valid_email#gmail.com']
You need to call add_personalization to the message object that you created, like this:
message.add_personalization(personalization)
Here's the full code with the fix:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Attachment, Mail
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException, Personalization, Bcc
import os
API_KEY = "real id"
lista = { "sentences": ["Sentence 1 <br>", "Sentence 2 <br>"] }
recips = ['email1#gmail.com', 'email2#gmail.com', 'email2#gmail.com']
to_emails = [To(email= 'one_valid_email#gmail.com']
personalization = Personalization()
personalization.add_to(To('one_valid_email#gmail.com'))
for bcc_addr in recips:
personalization.add_bcc(Bcc(bcc_addr))
message = Mail(
from_email=('emailsender#gmail.com'),
subject="email subject",
to_emails=to_emails,
is_multiple=True)
message.add_personalization(personalization)
message.dynamic_template_data = lista
message.template_id = 'real id'
try:
sendgrid_client = SendGridAPIClient(api_sendgrid)
response = sendgrid_client.send(message)
print(response.status_code)
#print(response.body)
#print(response.headers)
except Exception as e:
print(e.message)
return
Since your "sentences" dynamic template data is an array, you should likely loop through it too, so you can print each sentence. Try this in your template:
{{#each sentences}}
<div style="font-family: inherit; text-align: inherit">{{this}}</div>
{{/each}}
so I'm working on something that uses regex to search something from an email, which is fetched via imaplib module. Right now I can't get it to work, even after using str() function.
result, data = mail.fetch(x, '(RFC822)')
eemail = email.message_from_bytes(data[0][1])
print(str(eemail))
trying to regex it:
print(re.search("button", eemail))
Regex gives me no matches even after making the email a string object.
This is what I use:
import imaplib
import email
import re
mail = imaplib.IMAP4_SSL(SMTP_SERVER, SMTP_PORT)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
status, response = mail.search(None, '(UNSEEN)')
unread_msg_nums = response[0].split()
for e_id in unread_msg_nums:
_, response = mail.fetch(e_id, '(UID BODY[TEXT])')
b = email.message_from_string(response[0][1])
if b.is_multipart():
for payload in b.get_payload(decode=True):
print(re.search("button", payload.get_payload(decode=True)))
else:
print(re.search("button", b.get_payload(decode=True)))
I'am trying to add a header to a mail using sendGrid:
This is the code to send an email from the official website ,
string apikey = "......."
sg = sendgrid.SendGridAPIClient( apikey =apikey)
to_email = Email("....#gmail.com")
from_email =Email ("....")
subject= '...'
content=Content('..')
mail =Mail(...)
response = sg.client.mail.send.post(request_body=mail.get())
& it works fine,now to add a header I did (using this : https://github.com/sendgrid/smtpapi-python)
header = SMTPAPIHeader()
header.set_unique_args({'orderNumber':'123456'})
mail.add_header(header)
then
response = sg.client.mail.send.post(request_body=mail.get())
but I get :
in get(self)
70 headers = {}
71 for key in self.headers:
---> 72 headers.update(key.get())
73 mail["headers"] = headers
74
AttributeError: 'SMTPAPIHeader' object has no attribute 'get'
How ca, I solve this?
Yest indeed it was done with personalization:
mail.personalizations[0].add_header(Header("..","..."))
response = sg.client.mail.send.post(request_body=mail.get())
Try this, you can use set_headers method to set headers for sendgrid email.
import sendgrid
sg = sendgrid.SendGridClient("XXXX-UR-API-KEY-XXXXX")
message = sendgrid.Mail()
message.add_to('to#email.com')
message.set_from("from#email.com>")
message.set_subject("email subject")
message.set_html('html body')
message.set_headers({'X-Priority' : '2'}) #<=== To add priority
sg.send(message)