def send_mail(from_email, _to_email, subject, body, html=False, from_name="Gitcoin.co", cc_emails=None): # make sure this subscriber is saved to_email = _to_email get_or_save_email_subscriber(to_email, 'internal') # setup sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email, from_name) to_email = Email(to_email) contenttype = "text/plain" if not html else "text/html" # build content content = Content(contenttype, html) if html else Content( contenttype, body) if settings.DEBUG: to_email = Email( settings.CONTACT_EMAIL ) #just to be double secret sure of what were doing in dev subject = "[DEBUG] " + subject mail = Mail(from_email, subject, to_email, content) # build personalization (BCC + CC) p = Personalization() p.add_to(to_email) if cc_emails: #only add CCif not in prod for cc_addr in set(cc_emails): cc_addr = Email(cc_addr) if settings.DEBUG: cc_addr = to_email if cc_addr._email != to_email._email: p.add_to(cc_addr) p.add_bcc(Email(settings.BCC_EMAIL)) mail.add_personalization(p) # debug logs print("-- Sending Mail '{}' to {}".format(subject, _to_email)) # send mails response = sg.client.mail.send.post(request_body=mail.get()) return response
def send_email(to_str, subject, html_content): """ A function to send an email Arguments: to_str - email receivers (comma separated) subject - email subject html_content - email content Returns: success - flag if the action was succesful error - error message """ if SG_EMAIL_DISABLE: print("!!! SendGrid DISABLED !!!") return True, None # if we are testing functionality - ovewrite from/to if SG_TEST_EMAIL: print("!!! SendGrid TEST Mode. Overwriting from/to !!!") from_email = Email(SG_TEST_FROM) to_emails_ = _prep_to_list(SG_TEST_TO) else: from_email = Email(SG_FROM_EMAIL) to_emails_ = _prep_to_list(to_str) # excluding emails to_emails = [x for x in to_emails_ if x not in SG_EMAIL_EXCL] if len(to_emails) == 0: return False, "Empty recipient list" content = Content("text/html", html_content) mail = Mail( from_email=from_email, to_emails=to_emails, subject=subject, html_content=content, ) response = SG_CLIENT.client.mail.send.post(request_body=mail.get()) success = str(response.status_code).startswith("2") return success, response.status_code
def sendEmail(body, instance_name, send_to_emails, send_from, sg): # We assume this function is only called if notifications should be sent. completed_well = False host = platform.node() or "(unknown)" # Send emails for recipient in send_to_emails: # Prepare the email from_email = Email(send_from) to_email = Email(recipient) subject = 'Suspicious Recordings from Sensors' # Email Copy email_html_copy = f""" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title> { subject } </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> { body } <br/> <br/> <br/> <p> <small style="font-size: 7pt;color:#ccc;"> Sent from { instance_name } ({ host }) </small> </p> </body> </html> """ content = Content("text/html", email_html_copy) mail = Mail(from_email, subject, to_email, content) # Send the email response = sg.client.mail.send.post(request_body=mail.get()) # Check the response and return true if success (any HTTP code starting with 2) completed_well = str(response.status_code).startswith('2') print( f"email sent to '{recipient}' was { '' if completed_well else ' NOT '} successful" ) # Indicate whether everything worked as expected print("Notification sent to subscribers was " + ("successful" if completed_well else "not successful")) return completed_well
def send_mail(message_record): sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(message_record.user.email) to_email = Email(settings.COUNCIL_CLERK_EMAIL) subject = "Comment on {}".format(message_record.agenda_item.title) content = Content('text/html', message_record.content) mail = Mail(from_email=from_email, subject=subject, to_email=to_email, content=content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 200 or response.status_code == 202: return True else: log.error("Could not send an email from {} to {} about {}".format(from_email, to_email, subject)) log.error(response.body) log.error(response.status_code) return False
def send_sendgrid_email(email, html): # Setup when to send the email now = datetime.datetime.now() today8am = now.replace(hour=8, minute=0, second=0, microsecond=0) # Set the subject subject = "Your Daily NewsAI update" to_email = Email(email) content = Content("text/html", html) mail = Mail(Email(SENDGRID_SENDER, "NewsAI"), subject, to_email, content) mail.personalizations[0].set_send_at(int(today8am.strftime("%s"))) mail.personalizations[0].add_bcc(Email("*****@*****.**")) try: response = sg.client.mail.send.post(request_body=mail.get()) except urllib.HTTPError as e: print e return
def send_email(filename, email): ''' THIRD CELERY TASK ''' # link = "<a href='http://*****:*****@gmail') subject = filename to_email = Email(email) content = Content('text/html', link) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def send_mail(self): # sending an email print("Sending email to " + self.to_email) sg = sendgrid.SendGridAPIClient(apikey=self.mykey) content = Content("text/html", self.content) mail = Mail(self.from_email, str(self.subject), Email(self.to_email), content) response = sg.client.mail.send.post(request_body=mail.get()) return response, self.subject, content.value
def handle(self, *args, **options): """send email""" data = DataGetter.get_email_alert_data() done = [] for row in data: sendgrid_client = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email(os.environ['SENDER_EMAIL']) to_email = Email(row['email']) subject = "Hamburg alert for {}".format(row['movie_name']) content = Content("text/plain", "{} is releasing on {}".format(row['movie_name'],\ row['release_date'])) mail = Mail(from_email, subject, to_email, content) response = sendgrid_client.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: done.append(row['id']) EmailAlertModel.objects.filter(id__in=done).update(done=True)
def receiver_handler(receivers, new_mail): if receivers is not None: list_of_emails = receivers.split(';') for email_address in list_of_emails: if shared.validate_email(email_address): new_mail.personalizations[0].add_to(Email(email_address)) else: error_handler('The recipient email address ({}) is invalid.'.format(email_address))
def welcome_mail(sender, instance, **kwargs): if kwargs["created"]: user_email = instance.email sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY")) from_email = Email("*****@*****.**") to_email = Email(user_email) subject = "Welcome to contractAlchemy!" content = Content( "text/plain", "contractAlchemy is a tool that organizes your clients, jobs, parts, and invoices all in one place.\n\ Premium users gain access to all of our features with an unlimited number of records.\n\ Premium membership also includes the ability to select different themes for the website layout.\n\ Our free membership includes access to all features for up to 6 records at a time - 6 clients, 6 jobs, and so on.\n\ You can upgrade to premium at any time.", ) mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=mail.get())
def bcc_handler(bcc, new_mail): if bcc is not None: list_of_emails = bcc.split(';') for email_address in list_of_emails: if shared.validate_email(email_address): new_mail.personalizations[0].add_bcc(Email(email_address)) else: error_handler('The BCC email address ({}) is invalid.'.format(email_address))
def Cryptobot(currencie_name): try: headers = {'CB-VERSION': time.strftime("%Y-%m-%d")} rule = Rule.objects.get(currencie=currencie_name) r = requests.get("https://api.coinbase.com/v2/prices/" + "BTC-" + currencie_name + "/spot", headers=headers) # We check if the currencie exist if r.status_code < 200 or r.status_code >= 300: print("coinbase don't know this currencie here the full message.") print(r.json()) else: amount = float(r.json()['data']['amount']) print(amount) # If the value in under the minimum or upper the maximum we send a mail and create an alert if rule.value_min is not None and rule.value_min > amount or rule.value_max is not None and rule.value_max < amount: # Configure sendgrid to send mail sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("*****@*****.**") # !!!! Change email here for test !!!! to_email = Email("*****@*****.**") subject = "An Alert have been raise" content = Content( "text/plain", "An Alert have been raise, the bitcoin is now at " + str(amount) + currencie_name) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) # We check if the mail have been send if response.status_code < 200 or response.status_code >= 300: Alert.objects.create(message="Sending the mail have fail", currencie=currencie_name) else: Alert.objects.create( message= "An Alert have been raise, the bitcoin is now at " + str(amount) + currencie_name, currencie=currencie_name) # we launch the task after 5 second if everything work Cryptobot.apply_async((currencie_name, ), countdown=5) except ObjectDoesNotExist: print( "There is no rule for " + currencie_name + " go to http://127.0.0.1:8000/crypto/rules/ to create one, and name the currencie with one of the currencie you can see with python3 manage.py currencie_list" )
def send_mail(to_email, subject, message): sg = sendgrid.SendGridAPIClient(apikey=get_api_key()) content_message = get_content_message(to_email, message) mail = Mail( Email('*****@*****.**'), subject, Email(to_email), Content('text/plain', content_message)) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) if response.status_code >= 400: return False return True
def send_feedback(user, message): substitutions = [Substitution('-message-', message.encode('utf-8'))] mails = [Email(email=admin[1], name=admin[0]) for admin in settings.ADMINS] sendgrid_api( obtain_mail(personalization=obtain_personalization(user, substitutions, to_mails=mails), template=settings.SENDGRID_FEEDBACK))
def send(from_email, to_email, subject, content, content_type="text/plain"): sg = SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email) to_email = Email(to_email) subject = "[pystock] {}".format(subject) content = Content(content_type, content) mail = Mail(from_email, subject, to_email, content) try: response = sg.client.mail.send.post(request_body=mail.get()) except Exception: response = False if response and response.status_code != 202: logger.debug("Failed to send message: {}. Status code {}".format( content, response.status_code)) elif not response: logger.debug("Failed to send message: {}. response is {}".format( content, response))
def send_mail(from_email, _to_email, subject, body, html=False, from_name="Gitcoin.co", cc_emails=None): """Send email via SendGrid.""" # make sure this subscriber is saved to_email = _to_email get_or_save_email_subscriber(to_email, 'internal') # setup sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email, from_name) to_email = Email(to_email) contenttype = "text/plain" if not html else "text/html" # build content content = Content(contenttype, html) if html else Content(contenttype, body) if settings.IS_DEBUG_ENV: to_email = Email(settings.CONTACT_EMAIL) # just to be double secret sure of what were doing in dev subject = "[DEBUG] " + subject mail = Mail(from_email, subject, to_email, content) response = None # build personalization p = Personalization() p.add_to(to_email) if cc_emails: # only add CCif not in prod for cc_addr in set(cc_emails): cc_addr = Email(cc_addr) if settings.IS_DEBUG_ENV: cc_addr = to_email if cc_addr._email != to_email._email: p.add_to(cc_addr) mail.add_personalization(p) # debug logs print(f"-- Sending Mail '{subject}' to {_to_email}") # send mails try: response = sg.client.mail.send.post(request_body=mail.get()) except UnauthorizedError: print(f'-- Sendgrid Mail failure - Unauthorized - Check sendgrid credentials') except HTTPError as e: print(f'-- Sendgrid Mail failure - {e}') return response
def test_unicode_values_in_substitutions_helper(self): """ Test that the Substitutions helper accepts unicode values """ self.maxDiff = None """Minimum required to send an email""" mail = Mail() mail.from_email = Email("*****@*****.**") mail.subject = "Testing unicode substitutions with the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**")) personalization.add_substitution(Substitution("%city%", u"Αθήνα")) mail.add_personalization(personalization) mail.add_content(Content("text/plain", "some text here")) mail.add_content( Content("text/html", "<html><body>some text here</body></html>")) expected_result = { "content": [{ "type": "text/plain", "value": "some text here" }, { "type": "text/html", "value": "<html><body>some text here</body></html>" }], "from": { "email": "*****@*****.**" }, "personalizations": [{ "substitutions": { "%city%": u"Αθήνα" }, "to": [{ "email": "*****@*****.**" }] }], "subject": "Testing unicode substitutions with the SendGrid Python Library", } self.assertEqual(json.dumps(mail.get(), sort_keys=True), json.dumps(expected_result, sort_keys=True))
def create_mail(self): """ Creates email to send to this user """ to_email = Email(self.email) from_email = Email("*****@*****.**") subject = User.template_dict[self.template]['subject'] template_id = User.template_dict[self.template]['template_id'] content = Content("text/plain", "text") mail = Mail(from_email, subject, to_email, content) mail.personalizations[0].add_substitution( Substitution("-name-", self.name)) mail.personalizations[0].add_substitution( Substitution("-city-", "Denver")) mail.template_id = template_id return mail
def notify(note, email_address): # Say 'someone' if the byline is empty. try: who = note.byline or 'someone' subject = 'saythanks.io: {} sent a note!'.format(who) message = TEMPLATE.format(note.body, note.byline) from_address = Email('*****@*****.**', name="SayThanks.io") to_address = Email(email_address) content = Content('text/plain', message) mail = Mail(from_address, subject, to_address, content) response = sg.client.mail.send.post(request_body=mail.get()) except Exception as ex: pass
def _process_email_addr(self, email_addr): from_name, from_email = rfc822.parseaddr(email_addr) # Python sendgrid client should improve # sendgrid/helpers/mail/mail.py:164 if not from_name: from_name = None return Email(from_email, from_name)
def send_email(send_from, send_to, subject, message): """ Helper method to send emails via sendgrid Args: send_from: The email address of sender send_to: The email address of receiver subject: The subject of email message: The contents of email Returns: Nothin! """ from_email = Email(send_from) to_email = Email(send_to) content = Content("text/plain", message) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def sendCodeInEmail(email, code): try: SENDGRID_API_KEY = xl.getSendgridAPI_KEY() if not SENDGRID_API_KEY: return 500 sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = Email(xl.getEmailFrom()) to_email = Email(email) subject = xl.getEmailSubject() body_part1, body_part2 = xl.getEmailBody() content = Content( "text/html", "{} {} {}".format(body_part1, code, body_part2)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code except: log("send email failed for {}".format(email))
def send_email(html, from_email, to_email, subject): """Send html via email""" sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email(from_email) subject = subject to_email = Email(to_email) # Inline css in html html = inline_css(html) content = Content("text/html", html) 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
def formpage(request): if request.method == "POST": req = VisitRequests.objects.all().order_by('-timestamp') token = secrets.token_urlsafe(20) visitor_name = request.POST.get("visitor_name") staff_id = request.POST.get('staff') time = request.POST.get('time_in') visit_type = request.POST.get("visit_type") comment = request.POST.get("comment") staff = Staff.objects.get(id=staff_id) staff_email = staff.staff_email visitor = Visitor.objects.create(visitor_name=visitor_name) visit_request = VisitRequests.objects.create(staff=staff, visitor=visitor, comment=comment, token=token, status=None, timestamo=time, visit_type=visit_type) link = "http://192.168.1.179/portal/approval/" + staff_id + "/" + token visit_content = 'You have a waiting visitor' + '\n' + 'Name:' + visitor_name + '\n' + 'Purpose Of Visit:' + visit_type + '\n' + 'Additional Comment:' + comment + '\n' + link from_email = Email("*****@*****.**") to_email = Email(staff_email) subject = visitor_name content = Content("text/plain", visit_content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.headers) if response.status_code == 200: messages.add_message(request, messages.SUCCESS, _('Mail sent')) elif response.status_code == 202: messages.add_message(request, messages.SUCCESS, _('Mail sent for processing')) else: messages.add_message(request, messages.ERROR, _('Mail not sent')) return render(request, 'portal/all_requests.html', { 'requests': req, }) else: form = VisitorsForm() context = {'form': form} return render(request, 'portal/formpage.html', context)
def send_email_confirmation(recipients, projectName, amount, description): html = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>html title</title> <style type="text/css" media="screen" /> </head> <body> """ html += "<p>Dear donor,</p>" html += "<p>-------------------------------------------</p>" html += "<p>The project you donated: " + projectName + " has new money confirmaton.</p" html += "<p>The charity has claimed: " + amount + " dollars. </p>" html += "<p>This money is used in: " + description + " .</p>" html += "<p>We will keep updating you the project progress and money usage. You can also visit out website for more information!</p>" html += """ <p>-------------------------------------------</p> <p>Best regards,<br>TransACT team</p> <p>http://localhost:3001/ </p> </body> </html> """ subject = "TransACT - New Project Update!" message = Mail() for to_email in recipients: # Create new instance for each email personalization = Personalization() # Add email addresses to personalization instance personalization.add_to(Email(to_email)) # Add personalization instance to Mail object message.add_personalization(personalization) # Add data that is common to all personalizations message.from_email = Email('*****@*****.**') message.subject = subject message.add_content(Content('text/html', html)) client = SendGridAPIClient( "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" ) response = client.send(message) print(response)
def handle(self, *args, **options): if not hasattr(settings, 'SENDGRID_API_KEY'): return if not settings.SENDGRID_API_KEY: return sg_api = SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) msg_ids = EmailMessage.objects.filter(status__isnull=True).values('id') for msg_id in msg_ids: # We're going to be altering messages in the course of this loop, # so let's iterate over the IDs and not the message objects # themselves. # Note that values() returns a list of dicts, {'field_name': value}. message = EmailMessage.objects.get(id=msg_id['id']) from_email = Email("*****@*****.**") to_email = Email(message.address) try: subject = message.emailtype.subject.format( first_name=message.first_name, last_name=message.last_name) except KeyError: # If users have screwed up entering {first_name} or {last_name}, # format() will throw a KeyError. subject = 'About your ALA committee volunteering' try: body = message.emailtype.body.format( first_name=message.first_name, last_name=message.last_name) except KeyError: # This may look like a bad mail merge, but we can't anticipate # a substitute. body = message.emailtype.body content = Content("text/plain", body) mail = Mail(from_email, subject, to_email, content) response = sg_api.client.mail.send.post(request_body=mail.get()) message.status = response.status_code message.save()
def send_email(*, receivers: list, subject: str, content: str, celery_task=None): """ Kwargs: receivers [List[Str]]: A list of emails to send the mail. subject [Str]: The subject of the mail content [Str]: The HTML content of the mail """ if not sg or not receivers: return None message = Mail( from_email=("*****@*****.**", "Ora"), # to_emails="*****@*****.**", subject=subject, html_content=content, # subject='Sending with Twilio SendGrid is Fun', # html_content='<strong>and easy to do anywhere, even with Python</strong>' ) # Add the receivers to_list = Personalization() for recv in receivers: # to_list.add_to(Email("EMAIL ADDRESS")) to_list.add_to(Email(recv)) # Inject the receivers to the email message.add_personalization(to_list) status_code = 500 try: response = sg.send(message) status_code = response.status_code except HTTPError as exc: status_code = 401 if celery_task: mark_task_as_failed(celery_task, reason=str(exc)) except IncompleteRead as exc: status_code = 401 if celery_task: mark_task_as_failed(celery_task, reason=str(exc)) except UnauthorizedError as exc: status_code = 401 if celery_task: mark_task_as_failed(celery_task, reason=str(exc)) # return { # "status_code": response.status_code, # "body": response.body, # "headers": response.headers, # } return status_code
def sendgridmail(user, TEXT): sg = sendgrid.SendGridAPIClient( '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' ) from_email = Email( "*****@*****.**") # Change to your verified sender to_email = To(user) # Change to your recipient subject = "Sending with SendGrid is Fun" content = Content("text/plain", TEXT) mail = Mail(from_email, to_email, subject, content)
def send_email_verification(email): """Send a verification code to an email address using the SendGrid API. The verification code and the expiry are stored in a server side session to compare against user input. Args: email (str): Email address to send the verification to Raises: ValidationError: Verification request failed due to invalid arguments EmailVerificationError: Verification request failed for a reason not related to the arguments """ verification_code = str(randint(100000, 999999)) # Save the verification code and expiry in a server side session session['email_attestation'] = { 'email': generate_password_hash(email), 'code': verification_code, 'expiry': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) } # Build the email containing the verification code from_email = Email(settings.SENDGRID_FROM_EMAIL) to_email = Email(email) subject = 'Your Origin Verification Code' message = 'Your Origin verification code is {}.'.format( verification_code) message += ' It will expire in 30 minutes.' content = Content('text/plain', message) mail = Mail(from_email, subject, to_email, content) try: _send_email_using_sendgrid(mail) except Exception as exc: logger.exception(exc) # SendGrid does not have its own error types but might in the future # See https://github.com/sendgrid/sendgrid-python/issues/315 raise EmailVerificationError( 'Could not send verification code. Please try again shortly.') return VerificationServiceResponse()
def _send_via_sendgrid(subject, body): sg = SendGridAPIClient() from_email = Email(SOURCE_EMAIL) to_email = To(TARGET_EMAIL) content = Content("text/plain", body) email = Mail(from_email, to_email, subject, content) response = sg.client.mail.send.post(request_body=email.get()) logger.info(response.status_code) logger.info(response.body) logger.info(response.headers)