def SendEmail(to, subject, content, content_type='text/plain'): """Sends an email from a preconfigured sendgrid account. Blocking. Args: to: str. Email address. Email recipient (addressee). subject: str. Email subject. content: str. Email body. Should match content_type. content_type: str. Mime type. Raises: Exception. If sending email failed (status code is not 200 nor 202). """ response = _SEND_GRID_CLIENT.client.mail.send.post(request_body=mail.Mail( _FROM, subject, mail.Email(to), mail.Content(content_type, content)).get()) if response.status_code not in (200, 202): raise Exception('Error sending email to=%s subject=%s\n%s\n%s' % ( to, subject, response.status_code, response.body))
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")
import sendgrid from sendgrid.helpers import mail api = sendgrid.SendGridAPIClient(apikey='INSERT API KEY HERE') recipient = mail.Email('*****@*****.**') sender = mail.Email('*****@*****.**', 'Sender Name') subject = 'Email Subject' body = mail.Content('text/html', 'Email Body Here') email = mail.Mail(sender, subject, recipient, body) response = api.client.mail.send.post(request_body=email.get()) print(response.status_code) print(response.body) print(response.headers)
def make_message(to: str, subject: str, body: str) -> mail.Mail: to_email = mail.Email(to) content = mail.Content("text/plain", body) return mail.Mail(DEFAULT_SENDER, subject, to_email, content)
import sendgrid from sendgrid.helpers import mail def _read_key_file(fname): with open(fname) as fd: return fd.read().strip() # Get API key (shared for workshop account) SENDGRID_KEY_PATH = "/nfs/jsalt/share/sendgrid.key" SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY", None) if SENDGRID_API_KEY is None: SENDGRID_API_KEY = _read_key_file(SENDGRID_KEY_PATH) DEFAULT_SENDER = mail.Email("*****@*****.**", name="Cookie Monster") LOCALTZ = pytz.timezone("US/Eastern") def make_message(to: str, subject: str, body: str) -> mail.Mail: to_email = mail.Email(to) content = mail.Content("text/plain", body) return mail.Mail(DEFAULT_SENDER, subject, to_email, content) def send_message(message: mail.Mail): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) response = sg.client.mail.send.post(request_body=message.get()) return response
Raises: Exception. If sending email failed (status code is not 200 nor 202). """ response = _SEND_GRID_CLIENT.client.mail.send.post(request_body=mail.Mail( _FROM, subject, mail.Email(to), mail.Content(content_type, content)).get()) if response.status_code not in (200, 202): raise Exception('Error sending email to=%s subject=%s\n%s\n%s' % ( to, subject, response.status_code, response.body)) def SendEmailAsync(to, subject, content, content_type='text/plain'): """Sends an email from a preconfigured sendgrid account. Non-blocking. Args: See SendEmail. """ return executor.Executor.BACKGROUND_THREAD.Execute( SendEmail, to, subject, content, content_type) # Preconfigured email account for sending emails. # TODO: Remove the key from source code. _SEND_GRID_API_KEY = ( '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') # SendGrid email service client. _SEND_GRID_CLIENT = sendgrid.SendGridAPIClient(apikey=_SEND_GRID_API_KEY) # Email sender identity (appears in the email's 'from' line). _FROM = mail.Email( email='*****@*****.**', name='Volleyball in Warsaw')
def _create_email_address( from_email_address: str, from_email_name: str ) -> mail_helpers.Email: """Create an email address with a name to personalize emails.""" return mail_helpers.Email(from_email_address, from_email_name)
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)
def send_email_via_sendgrid(): """A background task that sends an email via SendGrid.""" data = json.loads(request.get_data(as_text=True)) recipient_email = data.get("recipient_email") sender_email = data.get("sender_email") sender_name = data.get("sender_name") email_subject = data.get("email_subject") email_body = data.get("email_body") unsubscribe_group = data.get("unsubscribe_group") attachment_content_b64 = data.get("attachment_content_b64") attachment_filename = data.get("attachment_filename") attachment_filetype = data.get("attachment_filetype") if is_local(): # localhost (not really sending the email) logging.warning( "SEND EMAIL: Not really sending email because we're on localhost.") logging.warning("Recipient: {}".format(recipient_email)) logging.warning("Sender: {0}, {1}".format(sender_name, sender_email)) logging.warning("Subject: {}".format(email_subject)) logging.warning("Body: {}".format(email_body)) return "{sender_email} {email_subject}".format( sender_email=sender_email, email_subject=email_subject) else: # production (sending the email via SendGrid) if request.headers.get("X-AppEngine-QueueName"): # If the request has this header (X-AppEngine-QueueName), then it really came from Google Cloud Tasks. # Third-party requests that contain headers started with X are stripped of these headers once they hit GAE # servers. That's why no one can fake these headers. # SendGrid setup sg = SendGridAPIClient(api_key=AppSettings.get().sendgrid_api_key) # Set up email message email_message = Mail(from_email=mail.Email(email=sender_email, name=sender_name), to_emails=recipient_email, subject=email_subject, html_content=email_body) if attachment_content_b64 and attachment_content_b64 is not None and attachment_content_b64 != "": attachment = Attachment() attachment.content = attachment_content_b64 attachment.type = "text/{}".format(attachment_filetype) attachment.filename = attachment_filename attachment.disposition = "attachment" email_message.add_attachment(attachment) # Unsubscribe group (ASM) if unsubscribe_group: try: email_message.asm(Asm(group_id=int(unsubscribe_group))) except Exception as e: pass try: response = sg.send(email_message) logging.info(response.status_code) logging.info(response.body) logging.info(response.headers) except Exception as e: logging.error(str(e)) return "true"
from sendgrid.helpers import mail try: # Python 3 import urllib.request as urllib except ImportError: # Python 2 import urllib2 as urllib SENDGRID_API_KEY = "YOUR_SENDGRID_API_KEY" SENDGRID_SENDER_EMAIL = "*****@*****.**" SENDGRID_SENDER_NAME = "From Name" SENDGRID_RECIPIENT_EMAIL = "*****@*****.**" sg = sendgrid.SendGridAPIClient(apikey = SENDGRID_API_KEY) from_email = mail.Email(SENDGRID_SENDER_EMAIL, SENDGRID_SENDER_NAME) to_email = mail.Email(SENDGRID_RECIPIENT_EMAIL) subject = "Status for Today" # For plain text content content = mail.Content("text/plain", "Sensor is Offline") # For HTML content #content = mail.Content("text/html", "<html><body><h1>Station is Offline</h1></body></html>") message = mail.Mail(from_email, subject, to_email, content) try: response = sg.client.mail.send.post(request_body=message.get()) except urllib.HTTPError as e: