def send_via_sendgrid(sender_email, sender_name, receiver_email, email_subject, content): SENDGRID_API_KEY = get_sendgrid_api_key( ) # make sure to create this get_sendgrid_api_key() function in utils/secrets.py first sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY) email_message = sendgrid_mail.Mail() email_message.set_from(sendgrid_mail.Email(sender_email, sender_name)) email_message.set_subject(email_subject) email_message.add_content(sendgrid_mail.Content("text/html", content)) personalization = sendgrid_mail.Personalization() personalization.add_to(sendgrid_mail.Email(receiver_email)) email_message.add_personalization(personalization) try: response = sg.client.mail.send.post(request_body=email_message.get()) if str( response.status_code )[:1] != "2": # success codes start with 2, for example 200, 201, 202, ... logging.error("status code: " + str(response.status_code)) logging.error("headers: " + str(response.headers)) return logging.error("body: " + str(response.body)) except Exception as e: logging.error("Error with sending via sendgrid.") return logging.error(e.message)
def send_email(self, email: mail_.Email) -> bool: mail = sg_mail.Mail() personalization = sg_mail.Personalization() mail.set_from(sendgrid.Email(email.sender[1], email.sender[0])) mail.set_subject(email.subject) mail.add_content(sg_mail.Content("text/plain", email.content)) for recipient in email.recipients: personalization.add_to(sendgrid.Email(recipient)) if email.cc: for recipient in email.cc: personalization.add_cc(sendgrid.Email(recipient)) if email.bcc: for recipient in email.bcc: personalization.add_bcc(sendgrid.Email(recipient)) mail.add_personalization(personalization) response = self._sg_client.client.mail.send.post( request_body=mail.get()) if response.status_code in [202, 250]: return True elif response.status_code == 421: raise exceptions_.ServiceRateLimitException(self.name) elif response.status_code in [450, 550, 551, 552, 553]: exceptions_.InvalidRecipientException(self.name) else: exceptions_.GenericEmailServiceException(self.name) return False
def send_fax_as_email(from_, to, status, pages, error_code, error_message, content, content_type): message = mail.Mail() message.from_email = mail.Email('{}{}@{}'.format( app.config['FAX_EMAIL_PREFIX'], from_, app.config['INBOUND_EMAIL_DOMAIN'])) message.subject = 'Incoming fax' personalization = mail.Personalization() personalization.add_to(mail.Email(model.email_from_number(to))) message.add_personalization(personalization) message.add_content( mail.Content( 'text/html', ''' <table> <tr><th>From</th><td>{from_}</td></tr> <tr><th>To</th><td>{to}</td></tr> <tr><th>Status</th><td>{status}</td></tr> <tr><th>Pages</th><td>{pages}</td></tr> <tr><th>Fax Error Code</th><td>{error_code}</td> <tr><th>Fax Error Message</th><td>{error_message}</td> </table> '''.format(**locals()))) if content: attachment = mail.Attachment() attachment.content = base64.b64encode(content).decode('ascii') attachment.type = content_type attachment.filename = 'fax.pdf' attachment.disposition = "attachment" attachment.content_id = "Fax" message.add_attachment(attachment) data = message.get() app.sendgrid_client.client.mail.send.post(request_body=data)
def send_email(app, template_name, to=None, to_name=None, sender=None, sender_name=None, cc_sender=True, subject=None, attachments=None, **kwargs): app_settings = EMAIL_APP_SETTINGS[app] template = app_settings['templates'][template_name] if sender: sender = mail.Email(sender, sender_name) from_ = mail.Email(app_settings['from_email'], sender_name or app_settings['default_from_name']) to = mail.Email(to, to_name) # Forward name parameters to the template. kwargs['sender_name'] = sender_name or (sender.email if sender else 'anonymous') kwargs['to_name'] = to_name # Create the text and HTML bodies of the email. text = textwrap.dedent(template['text_body']) % kwargs html = app_settings['html'] % { 'body': textwrap.dedent(template['html_body']) % kwargs, } # Construct the email and send it. message = mail.Mail() message.add_category(mail.Category(template_name)) p = mail.Personalization() p.add_to(to) if sender: if cc_sender: p.add_cc(sender) message.reply_to = sender message.add_personalization(p) message.from_email = from_ message.subject = subject or (template['subject'] % kwargs) message.add_content(mail.Content('text/plain', text)) message.add_content(mail.Content('text/html', html)) if attachments: # Attachments should be a list of tuples of (filename, data). for filename, data in attachments: a = mail.Attachment() mimetype, _ = mimetypes.guess_type(filename) a.filename = filename a.type = mimetype a.content = base64.b64encode(data) message.add_attachment(a) try: _sendgrid_api.client.mail.send.post(request_body=message.get()) except Exception as e: logging.error('Failed to send email from %s to %s', from_.email, to.email) logging.error('Sendgrid error: %r', e) logging.debug(json.dumps(message.get())) raise errors.ExternalError('Could not send email') logging.debug('Sent email from %s to %s', from_.email, to.email)
def send_email(to, subject, body, cc=(), from_name='Ok', link=None, link_text="Sign in", template='email/notification.html', reply_to=None, **kwargs): """ Send an email using sendgrid. Usage: send_email('*****@*****.**', 'Hey from OK', 'hi', cc=['*****@*****.**'], reply_to='*****@*****.**') """ try: sg = _get_sendgrid_api_client() except ValueError as ex: logger.error('Unable to get sendgrid client: %s', ex) return False if not link: link = url_for('student.index', _external=True) html = render_template(template, subject=subject, body=body, link=link, link_text=link_text, **kwargs) mail = sg_helpers.Mail() mail.set_from(sg_helpers.Email('*****@*****.**', from_name)) mail.set_subject(subject) mail.add_content(sg_helpers.Content("text/html", emailFormat(html))) if reply_to: mail.set_reply_to(sg_helpers.Email(reply_to)) personalization = sg_helpers.Personalization() personalization.add_to(sg_helpers.Email(to)) for recipient in cc: personalization.add_cc(sg_helpers.Email(recipient)) mail.add_personalization(personalization) try: response = sg.client.mail.send.post(request_body=mail.get()) except HTTPError: logger.error("Could not send the email", exc_info=True) return False if response.status_code != 202: logger.error("Could not send email: {} - {}".format( response.status_code, response.body)) return False return True
def send_message(sender, recipients, subject, body_text, body_html, attachments=None, ccs=None, bccs=None, categories=None, send=True): mail = sgh.Mail() mail.from_email = sgh.Email(sender.email, sender.name) mail.subject = subject for recipient in recipients: personalization = sgh.Personalization() personalization.add_to(sgh.Email(recipient.email, recipient.name)) if ccs: for cc in ccs: personalization.add_cc(sgh.Email(cc.email)) if bccs: for bcc in bccs: personalization.add_bcc(sgh.Email(bcc.email)) mail.add_personalization(personalization) mail.add_content(sgh.Content("text/plain", body_text)) mail.add_content(sgh.Content("text/html", body_html)) if attachments: for attach in attachments: attachment = sgh.Attachment() attachment.set_content(attach.content) attachment.set_type(attach.type) attachment.set_filename(attach.filename) attachment.set_disposition(attach.disposition) attachment.set_content_id(attach.content_id) mail.add_attachment(attachment) if categories: for category in categories: mail.add_category(sgh.Category(category)) if send: if os.environ.get('REDIS_URL') is not None: send_email.delay(body=mail.get()) else: import sendgrid sg_api = sendgrid.SendGridAPIClient( apikey=constants.SENDGRID_API_KEY) return sg_api.client.mail.send.post(request_body=mail.get())
def _add_recipients(email, email_recipients): """Add multiple recipients to the sendgrid email object. Args: email (SendGrid): SendGrid mail object email_recipients (Str): comma-separated text of the email recipients Returns: SendGrid: SendGrid mail object with multiple recipients. """ personalization = mail.Personalization() recipients = email_recipients.split(',') for recipient in recipients: personalization.add_to(mail.Email(recipient)) email.add_personalization(personalization) return email
def send_email_back(recipient, subject, attachments, text_content=None, html_content=None): from sendgrid.helpers import mail from sendgrid.helpers.mail import Attachment import premailer logging.info("sending mail to %s (%s/%s)", recipient, SENDGRID_API_KEY, SENDGRID_SENDER) to_email = mail.Email(recipient) from_email = mail.Email(SENDGRID_SENDER) message = mail.Mail() message.set_from(from_email) message.set_subject(subject) personalization = mail.Personalization() personalization.add_to(to_email) message.add_personalization(personalization) if not text_content and not html_content: message.add_content(mail.Content("text/plain", global_body)) if text_content: message.add_content(mail.Content("text/plain", text_content)) if html_content: message.add_content(mail.Content("text/html", html_content)) for att in attachments: data = att["data"] file_name = att["name"] if file_name.endswith(".htm") or file_name.endswith(".html"): stub_css = "https://%s.appspot.com/css/stub.css" % app_identity.get_application_id() data = re.sub( r'\"D:\\ssis\\SecureMail\\SecureMailTest\\MailItemImages\\BankB1\.gifstyle\.css
.*\"', '"%s"' % stub_css, data) logging.info("before transform(%s) %s", type(data), data) logging.info("using premailer for %s", file_name) data = data.decode("utf8") p = premailer.Premailer(data) data = p.transform().encode("utf8") logging.info("after transform(%s) %s", type(data), data) attachment = Attachment() attachment.set_content(base64.b64encode(data)) attachment.set_type(att["type"]) attachment.set_filename(att["name"]) attachment.set_disposition("attachment") attachment.set_content_id(att["name"]) message.add_attachment(attachment) data = json.dumps(message.get()) logging.debug("sending %s", data) headers = { "Authorization": 'Bearer {0}'.format(SENDGRID_API_KEY), "Content-Type": "application/json", "Accept": 'application/json' } response = urlfetch.fetch( url="https://api.sendgrid.com/v3/mail/send", payload=data, method=urlfetch.POST, headers=headers) if response.status_code > 299: logging.error("response %s(%s)", response.content, response.status_code) else: logging.info("response %s(%s)", response.content, response.status_code) if response.status_code > 299: raise Exception("Failed to call sendgrid API")
def sendEmail(cls, params, debug=False): to = params['to'] subject = params['subject'] html = params['html'] attachments_json = params.get('attachments') reply_to = params.get('reply_to') # make to a list if it isn't already if isinstance(to, str): to = [to] body = helpers.strip_html(html) # attachments had to be encoded to send properly, so we decode them here attachments = attachments_json and json.loads(attachments_json) or None message = sgmail.Mail() message.from_email = sgmail.Email(SENDER_EMAIL) message.subject = subject if attachments: for data in attachments: attachment = sgmail.Attachment() attachment.content = base64.b64decode(data['content']) attachment.content_id = data['content_id'] attachment.disposition = data.get( 'disposition', 'inline') # 'attachment' for non-embedded attachment.filename = data['filename'] attachment.type = data['type'] message.add_attachment(attachment) # NOTE that plain must come first message.add_content(sgmail.Content('text/plain', body)) message.add_content(sgmail.Content('text/html', html)) personalization = sgmail.Personalization() for to_email in to: personalization.add_to(sgmail.Email(to_email)) message.add_personalization(personalization) if reply_to: message.reply_to = sgmail.Email(reply_to) if not debug: if SENDGRID_API_KEY: # an error here logs the status code but not the message # which is way more helpful, so we get it manually try: cls.SENDGRID.client.mail.send.post( request_body=message.get()) except urllib.error.HTTPError as e: cls.LOGGER.error(e.read()) else: cls.LOGGER.info( 'Have email to send but no SendGrid API key exists.') else: kwargs = { 'sender': SENDER_EMAIL, 'subject': subject, 'body': body, 'html': html } if attachments: mail_attachments = [] for data in attachments: mail_attachment = [ data['filename'], base64.b64decode(data['content']), data['content_id'] ] mail_attachments.append(mail_attachment) kwargs['attachments'] = mail_attachments if reply_to: kwargs['reply_to'] = reply_to for to_email in to: kwargs['to'] = to_email cls.LOGGER.info(kwargs)