Anyone please help, I am using sendgrid v3 api. But I cannot find any way to send an email to multiple recipients. Thank in advance.
import sendgrid
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey="SG.xxxxxxxx")
from_email = Email("FROM EMAIL ADDRESS")
to_email = Email("TO EMAIL ADDRESS")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
I want to send email to multiple recipient. Like to_mail = " xxx#gmail.com, yyy#gmail.com".
Note that with the code of the other answers here, the recipients of the email will see each others emails address in the TO field. To avoid this one has to use a separate Personalization object for every email address:
def SendEmail():
sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
from_email = Email ("FROM EMAIL ADDRESS")
person1 = Personalization()
person1.add_to(Email ("EMAIL ADDRESS 1"))
person2 = Personalization()
person2.add_to(Email ("EMAIL ADDRESS 2"))
subject = "EMAIL SUBJECT"
content = Content ("text/plain", "EMAIL BODY")
mail = Mail (from_email, subject, None, content)
mail.add_personalization(person1)
mail.add_personalization(person2)
response = sg.client.mail.send.post (request_body=mail.get())
return response.status_code == 202
You can send an email to multiple recipients by listing them in the to_emails parameter of the Mail constructor:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *
message = Mail(
from_email='sender#example.com',
to_emails=[To('test#example.com'), To('test2#example.com')],
subject='Subject line',
text_content='This is the message of your email',
)
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)
With this configuration, each recipient will be able to see each other listed on the email. To avoid this, use the is_multiple parameter to tell Sendgrid to create a new Personalization for each recipient:
message = Mail(
from_email='sender#example.com',
to_emails=[To('test#example.com'), To('test2#example.com')],
subject='Subject line',
text_content='This is the message of your email',
is_multiple=True # Avoid listing all recipients on the email
)
To send email to multiple recicpent in sendgrid v3.
import time
import sendgrid
import os
print "Send email to multiple user"
sg = sendgrid.SendGridAPIClient(apikey='your sendrid key here')
data = {
"personalizations": [
{
"to": [{
"email": "adiii#gmail.com"
}, {
"email": "youremail#gmail.com"
}],
"subject": "Multiple recipent Testing"
}
],
"from": {
"email": "Alert#gmail.com"
},
"content": [
{
"type": "text/html",
"value": "<h3 style=\"color: #ff0000;\">These checks are silenced please check dashboard. Click HERE</h3> <br><br> <h3>For any query please contact DevOps Team<h3>"
}
]
}
response = sg.client.mail.send.post(request_body=data)
print(response.status_code)
if response.status_code == 202:
print "email sent"
else:
print("Checking body",response.body)
https://libraries.io/github/sendwithus/sendgrid-python
You can update your code in the below way. You can find the same in mail_example.py present in Sendgrid's package.
personalization = get_mock_personalization_dict()
mail.add_personalization(build_personalization(personalization))
def get_mock_personalization_dict():
"""Get a dict of personalization mock."""
mock_pers = dict()
mock_pers['to_list'] = [Email("test1#example.com",
"Example User"),
Email("test2#example.com",
"Example User")]
return mock_pers
def build_personalization(personalization):
"""Build personalization mock instance from a mock dict"""
mock_personalization = Personalization()
for to_addr in personalization['to_list']:
mock_personalization.add_to(to_addr)
return mock_personalization
Based on Subhrajyoti Das answer, I wrote the following code, that is a simpler version of the mail_example.py example of sending email to multiple recipient.
def SendEmail():
sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
from_email = Email ("FROM EMAIL ADDRESS")
to_list = Personalization()
to_list.add_to (Email ("EMAIL ADDRESS 1"))
to_list.add_to (Email ("EMAIL ADDRESS 2"))
to_list.add_to (Email ("EMAIL ADDRESS 3"))
subject = "EMAIL SUBJECT"
content = Content ("text/plain", "EMAIL BODY")
mail = Mail (from_email, None, subject, content)
mail.add_personalization (to_list)
response = sg.client.mail.send.post (request_body=mail.get())
return response.status_code == 202
You can pass a list of strings.
message = Mail(
from_email='sender#email.com',
to_emails=['xxx#email.com', 'yyy#email.com'],
subject='subject',
html_content='content')
sg = SendGridAPIClient('SENDGRID_API_KEY')
response = sg.send(message)
Related
I made a contact form, I tested with the mailtrap service and it works I receive the messages well.
But when I put the smpt parameters for a real mail account I have this error message
SMTPRecipientsRefused at /contact/
{'info#mysite.net': (550, b'relay not permitted: you must be authenticated to send messages')}
the smtp server and the mail account is on the host alwasdata.net, but I tested with an outloock account it's the same thing always this same error. it seems to come from the line in the contact method:
message,
'info#mysite.net',
['info#othersite.net'],
fail_silently=False,
in settings.py i have this config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = "info#mysite.net"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST = 'smtp-blablabla.net'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
in a views.py
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = "Message d'un visiteur sur votre site"
body = {
'Nom': form.cleaned_data['first_name'],
'Tel': form.cleaned_data['tel'],
'Email': form.cleaned_data['email'],
'Message':form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(
subject,
message,
'info#mysite.net',
['info#othersite.net'],
fail_silently=False,
)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('/')
form = ContactForm()
return render(request,'pages/email_form.html',{'form':form})
the forms.py
from django import forms
class ContactForm(forms.Form):
first_name = forms.CharField(max_length=100, required=True)
tel = forms.CharField(max_length=15, required=True)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea, required=True)
I changed a few parameters:
I put all the email addresses on the servers where my site is hosted,
try:
send_mail(
subject,
message,
'info#mysite.net',
['info#mysite.net'],
fail_silently=False,
)
and at my host I changed the parameters of the mail server so that it redirects to the email address that I was targeting. Now it's work
Hi Iam newbie to Django,
I written an function to send email from any user who need to know more info about the trip.
I didn't know to how to collect posted user email id from user database. need help.
def PostDetailView(request, pk):
context = {}
context["data"] = Post.objects.get(id=pk)
if request.method == "POST":
name = request.POST['uName']
# phone = request.POST["phone"]
email = request.POST['uEmail']
desc = request.POST['uDes']
userEmail = I need to assign email id of this trip posted user
subject = 'Iam Interested in your Trip'
message = f'Hi Iam {name}, Iam Interested you trip. Please share more details on {email} {desc}'
email_from = email
recipient_list = [userEmail, ]
send_mail( subject, message, email_from, recipient_list, desc )
messages.success(request, 'Message Sent Successfully.')
return render(request, 'ads/detail.html',context)
return render(request, 'ads/detail.html',context)
Need help to fix this.
I think the posted user is the current authenticated user ?
so you can get email:
userEmail = request.user.email
def getbodyinbox():
service = build('gmail', 'v1', credentials=creds)
label_name = "READ-BY-SCRIPT"
label_id = 'Label_8507504117657095973'
results = service.users().messages().list(
userId='me', q="-label:"+label_name, maxResults=1).execute()
messages = results.get('messages', [])
body = []
if not messages:
body = "no messages"
return body
else:
for message in messages:
msg = service.users().messages().get(
userId='me', id=message['id']).execute()
labels = msg['labelIds']
if "INBOX" in labels:
headers = msg['payload']['headers']
headers = str(headers)
print(headers)
if "class_ix" in headers:
body.append(msg['payload']['parts'])
if 'data' in body[0][0]['body']:
body = base64.urlsafe_b64decode(
body[0][0]['body']['data'])
elif 'data' in body[0][1]['body']:
body = base64.urlsafe_b64decode(
body[0][1]['body']['data'])
body = str(body)
return body
print(getbodyinbox())
This is my code so far with the part that gets the credentials and all of the imports removed. It gets the body of the most recent email without a label 'READ-BY-SCRIPT' that also has the label INBOX. How can I get the subject of the email instead of the body?
Have a look at the message resource, MessagePart and header
The structure is the following:
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
and:
So, in other words, the subject is contained in the headers.
You can retrieve in Python with
headers = msg['payload']['headers']
subject= [i['value'] for i in headers if i["name"]=="Subject"]
I am trying to send an email to a specific recipient using python, but my code keeps setting the recipient as a BCC. How do I change this to set it as a normal To?
Thanks!
Here is my code
import smtplib
def send_email(subject, msg):
login = "My_email"
password = "password"
reciever = "recipient#gmail.com"
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(login, password)
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail(login, reciever, message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
subject = "Test email"
Sensor_Message = "This has worked"
send_email(subject, Sensor_Message)
I don't know python, but here is what I think the problem is: your message does not contain a To: or Cc: email header containing the recipient's email address.
Because the recipient's email address is in the list of RCPT TO commands sent over SMTP, but not in the email headers, the recipient's MUA (e.g. Gmail, Outlook, Thunderbird, etc.) treats it as a Bcc.
To fix this problem, make sure that the message contains a To: or Cc: header for the recipient.
Unrelated nitpick: the correct spelling is "receiver"
Good luck!
I'm trying to send an email via the Gmail API using Python, I want to iclude the signature. I'm able to successfuly get the signature using the following funciotn:
def addSignature(service):
sigtanture = service.users().settings().sendAs().get(userId=USER, sendAsEmail='example#example.com').execute()
return sigtanture['signature']
addSignature(SERVICE)
However, at the time of creating the message that I'll send, how do I append the Signature?
def CreateMessage(sender, to, subject, message_text, signature):
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message[???] = signature
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
I'm trying to send the message:
thebody = CreateMessage(USER, 'to#example.com', 'TestSignatureAPI','testing', addSignature(SERVICE))
SendMessage(SERVICE, USER, thebody)
Thank you!
Unfortunately there is no built-in feature to append the Gmail signature to your email
Instead, once you retrieve your signature as a text, you can simply append it manually to the end of your message_text before encoding.
See also here.
Assuming you retrieved the signature correctly and based on your code this means:
def CreateMessage(sender, to, subject, message_text, signature):
message_text = message_text + "\n" + signature
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message.attach(MIMEText(message_text_plain, 'plain'))
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body