def send(self, email_sender=None, email_recipient=None, email_subject=None, email_content=None, content_type=None, attachment=None): """Send an email. This uses the SendGrid API. https://github.com/sendgrid/sendgrid-python The minimum required info to send email are: sender, recipient, subject, and content (the body) Args: email_sender (str): The email sender. email_recipient (str): The email recipient. email_subject (str): The email subject. email_content (str): The email content (aka, body). content_type (str): The email content type. attachment (Attachment): A SendGrid Attachment. Raises: EmailSendError: An error with sending email has occurred. """ if not email_sender or not email_recipient: LOGGER.warning('Unable to send email: sender=%s, recipient=%s', email_sender, email_recipient) raise util_errors.EmailSendError email = mail.Mail() email.from_email = mail.Email(email_sender) email.subject = email_subject email.add_content(mail.Content(content_type, email_content)) email = self._add_recipients(email, email_recipient) if attachment: email.add_attachment(attachment) try: response = self._execute_send(email) except urllib.error.HTTPError as e: LOGGER.exception('Unable to send email: %s %s', e.code, e.reason) raise util_errors.EmailSendError if response.status_code == 202: LOGGER.info('Email accepted for delivery:\n%s', email_subject) else: LOGGER.error('Unable to send email:\n%s\n%s\n%s\n%s', email_subject, response.status_code, response.body, response.headers) raise util_errors.EmailSendError
def __init__(self, to=[], subject='', message='', cc=[]): self._from = mail.From("*****@*****.**", "Expert Traders") self.replyto = mail.ReplyTo('*****@*****.**', 'Expert Traders') self.to = [mail.To(i[0], i[1]) for i in to] if cc: self.cc = [mail.Cc(i[0], i[1]) for i in cc] else: self.cc = None self.subject = mail.Subject(subject) self.content = mail.Content(mail.MimeType.text, message) self.attachment = None
def send_email(self, new_user): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = mail.Email("*****@*****.**") subject = "New Baby Bet User" to_email = mail.Email("*****@*****.**") body = """There is a new user for Ianni Baby 2.0 Betting Service! Name: {} Email: {}""".format(new_user.name, new_user.email) content = mail.Content('text/plain', body) message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get())
def send_simple_message(recipient): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(recipient) from_email = mail.Email(SENDGRID_SENDER) subject = 'SpikeySales weekly lightning deal!' text = """Hurry up and grab the weekly lightning deal on Pedigree and other top dog feed brands.""" content = mail.Content('text/plain', text) message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get()) return response
def send_simple_message(recipient): # [START sendgrid-send] sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(recipient) from_email = mail.Email(SENDGRID_SENDER) subject = 'This is a test email' content = mail.Content('text/plain', 'Example message.') message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get()) return response
def send_newsletter(email, unsubscribe_token): text = text_template.format(unsubscribe=unsubscribe_token, email=email) html = html_template.format(unsubscribe=unsubscribe_token, email=email) message = mail.Mail() message.to = mail.To(email) message.subject = mail.Subject(subject) message.header = mail.Header( "List-Unsubscribe", "<mailto:[email protected]?subject=unsubscribe>") message.from_email = mail.From("*****@*****.**", "Thinktool Newsletter") message.reply_to = mail.ReplyTo("*****@*****.**", "Jonas Hvid (Thinktool)") message.content = [ mail.Content("text/plain", text), mail.Content("text/html", html), ] spit("last_sent.txt", text) spit("last_sent.html", html) sendgrid_client.send(message)
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='*****@*****.**') """ 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 urllib.error.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 sendmail(group_id, to_addr=None, plain_text=None, creole_text=None, html=None, subject=None, from_addr=None): config = current_app.config # # do sanity checks first # if not config.get('HAS_SENDMAIL', False): return msg.bug("Sendmail not active in config.") if group_id not in config.get("SENDGRID_UNSUBSCRIBE_GROUPS", {}): return msg.bug("Sendgrid unsubscribe group_id {} not found.".format(group_id)) from_header = from_addr or config.get("SENDGRID_DEFAULT_FROM_ADDRESS", None) if not from_header: return msg.bug("missing 'from' address.") to_header = to_addr if not to_header: return msg.bug("missing 'to' address.") subject_header = subject or config.get("SENDGRID_DEFAULT_SUBJECT", None) if not from_header: return msg.bug("missing subject.") if plain_text: body = plain_text mimetype = "text/plain" if creole_text: body = parsing.creole2html(creole_text) mimetype = "text/html" if html: body = html mimetype = "text/html" if not body: return msg.bug("missing body contents (via 'creole_text' or 'html' parameters.") # # # # email_id = uuid.uuid4() # message.set_headers({'X-Fondum-EmailID': str(email_id)}); try: sg = sendgrid.SendGridAPIClient(apikey=config['SENDGRID_API_KEY']) message = h.Mail( h.Email(from_header), subject_header, h.Email(to_header), h.Content(mimetype, body) ) message.asm = h.ASM(group_id) response = sg.client.mail.send.post(request_body=message.get()) except sg_except.UnauthorizedError as e: return msg.bug("SENDGRID unauthorized error (check SENDGRID_API_KEY): {}".format(str(e))) except Exception as e: return msg.bug("SENDGRID general error: {}".format(str(e))) return msg.success("Message sent to {}".format(to_header))
def send_message(sender, recipients, subject, body_text, body_html, attachments=None, ccs=None, bccs=None, categories=None, send=True): sg_api = sendgrid.SendGridAPIClient(apikey=constants.SENDGRID_API_KEY) 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: return sg_api.client.mail.send.post(request_body=mail.get())
def send(_from_email, _to_email, subject, _body_plain, _body_html): """ :param _from_email: string email address :param _to_email: string email address :param subject: string email subject :param _body_plain: string email body :param _body_html: string email body with html markup :return: response from SendGrid mail client """ sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(_to_email) from_email = mail.Email(_from_email) #content = mail.Content('text/plain', _body_plain) content = mail.Content('text/html', _body_html) message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get()) return response
def create_email( self, to_list: List[str], subject: str, html_content: str, image: bytes = None, content_type: str = None, send_at: datetime = None, ) -> mail.Mail: """ Create a new sendgrid email object. Params: - to_list: List[str] - The recipients list. - subject: str - The email subject. - html_content: str - HTML text to fill the email. - image: bytes - A optional image to attachment in email. - content_type: str - The content type of the image. - send_at: datetime - The datetime when the email must be sended. Return: - message: Mail - The sendgrid email object. """ message = mail.Mail() message.from_email = mail.From(self.from_email) message.subject = mail.Subject(subject) _users_list = [] for _to in to_list: _users_list.append(mail.To(_to)) message.to = _users_list if image: ext = str(content_type).split("/")[1] timestamp = datetime.utcnow().strftime("%Y-%m-%d-%H%M%S") message.attachment = mail.Attachment( mail.FileContent(image), mail.FileName(f"event_image-{timestamp}.{ext}"), mail.FileType(str(content_type)), mail.Disposition("attachment"), ) if send_at: message.send_at = mail.SendAt(self.get_unix_time(send_at), p=0) message.content = mail.Content(mail.MimeType.html, html_content) return message
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_template(email, subject, template_name, context=None): """Construct and send an email with subject `subject` to `email`, using the named email template. """ context = context or {} html, _text = render_email_body(template_name, context) LOGGER.info("Generated email: %s", html) addressal = context.get("user") if SG: message = mail.Mail(mail.Email(settings.EMAIL_ADDRESS), subject, mail.Email(email, addressal), mail.Content("text/html", html)) response = SG.client.mail.send.post(request_body=message.get()) LOGGER.info("Sent '%s' email to %s (response %s)", template_name, email, response) else: LOGGER.info("SendGrid not available. Generated email: %s", html)
def send_template(email, subject, template_name, context={}): context = context.copy() html = render_to_string("email/" + template_name + ".djhtml", context) addressal = context.get("user") try: text = render_to_string("email/" + template_name + ".djtxt", context) except TemplateDoesNotExist: text = strip_tags(html) if SG: message = mail.Mail(mail.Email(settings.EMAIL_ADDRESS), subject, mail.Email(email, addressal), mail.Content("text/html", html)) response = SG.client.mail.send.post(request_body=message.get()) logger.info("Sent '%s' email to %s (response %s)", template_name, email, response) else: logger.info("SendGrid not available. Generated email: %s", html)
def send(self, to_email: List[str], subject: str, content: str, mime_type: str = 'text/plain'): try: from_email = mail.From(email=config.email.from_address, name=config.email.from_name) to_email = mail.To(to_email) m = mail.Mail(from_email, to_email, subject, mail.Content(mime_type, content)) m.reply_to = mail.ReplyTo(config.email.reply_to_address) res = self._sg.client.mail.send.post(request_body=m.get()) self.logger.info(f"sendgrid email sent", res=res) except Exception as e: print(e) raise exceptions.provider.Failed(f"Could not send email: {e}")
def send_mail(to_email_str, offer): stat2str = { 'accepted': 'Aceptada', 'ignored': 'Ignorada', 'rejected': 'Rechazada' } sg = sendgrid.SendGridAPIClient(apikey=connvars.sendgrid_apikey) from_email = sgm.Email("*****@*****.**") to_email = sgm.Email(to_email_str) subject = "Su oferta de trabajo ha sido %s" % stat2str[offer['status']] date_str = dateutil.parser.parse( offer['timestamp']).strftime('%d/%m/%Y %H:%M:%S') msg = 'Le informamos que su oferta de trabajo publicada el ' + date_str msg += ' ha sido ' + stat2str[ offer['status']] + '. Usted envió los siguientes datos:\n' msg += format_offer(offer) msg += '\nSe despide cordialmente,\n\nEquipo de ChileDevs\n\[email protected]\n' content = sgm.Content("text/plain", msg) mail = sgm.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def send_email(): to = request.form.get('to') if not to: return ('Please provide an email address in the "to" query string ' 'parameter.'), 400 sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(to) from_email = mail.Email(SENDGRID_SENDER) subject = 'This is a test email' content = mail.Content('text/plain', 'Example message.') message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get()) if response.status_code != 202: return 'An error occurred: {}'.format(response.body), 500 return 'Email sent.'
def send_simple_message(recipient): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(recipient) from_email = mail.Email(SENDGRID_SENDER) subject = 'This is a test email' content = mail.Content('text/plain', 'Example sendgrid message.') message = mail.Mail(from_email, subject, to_email, content) message.template_id = 'b9bcf210-ed49-416c-8bed-f70b0f831693' logging.info("send_simple_message before ") try: response = sg.client.mail.send.post(request_body=message.get()) except: print("Received Exception, exoiting()") exit() logging.info("send_simple_message after") print("***************************") logging.info("%s", response.status_code) print("***************************") logging.info("%s", response.headers) print("***************************") return response
def send_email(self, user): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = mail.Email("*****@*****.**") to_email = mail.Email("*****@*****.**") # sender = "*****@*****.**" subject = user.name + " has made a bet" body = """There is a new bet by {}! Date/Time: {} {} Gender: {} Hair Color: {} Length: {}" Weight: {} lbs {} oz""".format(user.name, user.date, user.time, user.gender, user.hair_color, user.length, user.pounds, user.ounces) content = mail.Content('text/plain', body) message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get())
def sendGridEmail(to,emailType,userid,password): sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(to) from_email = mail.Email(SENDGRID_SENDER) content="" if emailType=="newuser": subject = 'Your HCPDigital Insights account' content = 'userId:' + userid+'\n' content = content+'Password:'******'\n' content = content+'url:https://hcpdigitalinsights.azurewebsites.net' body = mail.Content('text/plain',content) else: subject = 'Password reset' content = content+'userId:' + userid+'\n' content = content+'Password:'******'\n' content = content+'url:https://hcpdigitalinsights.azurewebsites.net' message = mail.Mail(from_email, subject, to_email, body) response = sg.client.mail.send.post(request_body=message.get()) print(response.status_code) print(response._body)
def sendMail(self, **post): body = """ name: {} email: {} city: {} phone: {} square footage: {} rooms: {}""".format(post['name'], post['emailAddress'], post['city'], post['phone'], post['sqFootage'], post['rooms']) sg = sendgrid.SendGridAPIClient(apikey=Config.sendgridApiToken) to_email = mail.Email(Config.sendgridRecipient) from_email = mail.Email(Config.sendgridSender) subject = 'New Quote Request' content = mail.Content('text/plain', body) message = mail.Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=message.get()) return response
def post(self): logging.info("ReceiveEmailHandler: parsing the received body ") try: content_type = self.request.headers["Content-Type"] except: logging.info( "Received error while parsing Content type, Mail format not recognized" ) exit() # Attach content-type header to body so that email library can decode it correctly message = "Content-Type: " + self.request.headers[ "Content-Type"] + "\r\n" message += self.request.body parsed_mail = parse(message) ''' # Below functionality handles forwarding received mail #Currently for testing , forwaded mail to the sender itself. # TO DO: Providing GUI to see inbox and select sender for mail forwarding ''' if parsed_mail: sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) to_email = mail.Email(parsed_mail['from']) from_email = mail.Email(parsed_mail['to']) subject = parsed_mail['subject'] content = mail.Content('text/plain', parsed_mail['text']) message = mail.Mail(from_email, subject, to_email, content) try: response = sg.client.mail.send.post(request_body=message.get()) except: logging.info("Received error while forwarding email, exiting") else: logging.info("%s", response.status_code) logging.info("%s", response.headers)
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: print (e.read()) exit() # Print response from SendGrid service print(response) print(response.status_code)
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_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)