def send_sendgrid_template(template_name, template_params, subject, sender_name, sender_email, recipient_name, recipient_email): '''Send a message via the SendGrid API.''' if template_name.strip() == 'share-to-recipient-web': logging.info('ignoring share to recipient message') return if template_name not in _TEMPLATE_NAME_TO_TEMPLATE_ID: logging.ing('template id not found for template name ' + template_name + ': ignoring message') return template_id = _TEMPLATE_NAME_TO_TEMPLATE_ID[template_name] mail = Mail() personalization = Personalization() personalization.add_to(Email(recipient_email)) mail.add_personalization(personalization) sender_name = None if sender_email is None: sender_email = _FROM_ADDR sender_name = _FROM_NAME mail.set_from(Email(email=sender_email, name=sender_name)) if subject: mail.set_subject(subject) mail.set_template_id(template_id) _send(mail)
def make_envelope(to, type, email_args): if current_app and current_app.config.get("TESTING"): return None from grant.user.models import User user = User.get_by_email(to) info = get_info_lookup[type](email_args) if user and 'subscription' in info: sub = info['subscription'] if user and not is_subscribed(user.settings.email_subscriptions, sub): current_app.logger.debug(f'Ignoring send_email to {to} of type {type} because user is unsubscribed.') return None email = generate_email(type, email_args, user) mail = Mail( from_email=Email(SENDGRID_DEFAULT_FROM, SENDGRID_DEFAULT_FROMNAME), to_email=Email(to), subject=email['info']['subject'], ) mail.add_content(Content('text/plain', email['text'])) mail.add_content(Content('text/html', email['html'])) mail.___type = type mail.___to = to return mail
def _make_sendgrid_mail(self, message): mail = Mail() if message.sender: mail.from_email = Email(message.sender) else: mail.from_email = Email(self.default_sender) if message.subject: mail.subject = message.subject if message.recipients: if type(message.recipients) == list: personalization = Personalization() for recipient in message.recipients: personalization.add_to(Email(recipient)) mail.add_personalization(personalization) else: raise Exception("unsupported type yet") if message.body: mail.add_content(Content("text/plain", message.body)) if message.html: mail.add_content(Content("text/html", message.html)) if message.reply_to: mail.reply_to = Email(message.reply_to) return mail
def send_email(receiver_email, user_lang): """Send user account validation.""" _ = gettext.translation( 'account_validation', '/code/locale', languages=[user_lang] ).gettext sender = os.getenv('SENDER_EMAIL') token = jwt.encode( {'email': receiver_email}, os.getenv('JWT_SECRET'), algorithm='HS512' ).decode('utf-8') validate_message = _(( 'Hi! Please, click on this <a href="{url}/{token}">link</a> ' 'to validate your account.' )).format( url=os.getenv('ACCOUNT_VALIDATION_URL'), token=token ) sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email(sender) to_email = Email(receiver_email) subject = _("ROAp: account validation") content = Content("text/html", validate_message) mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=mail.get())
def test_equality_email_name(self): address = "*****@*****.**" name = "SomeName" email1 = Email(address, name) email2 = Email(address, name) self.assertEqual(email1, email2)
def sendMail(scheduled_time, url, price, name): sg = sendgrid.SendGridAPIClient( apikey= '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' ) from_email = Email("*****@*****.**") subject = "This is a test email." to_email = Email("*****@*****.**") content = Content('text/html', 'text') mail = Mail(from_email, subject, to_email, content) dynamic_template_data = { 'name': name, "price": price, "date": "Denver", "firstName": name, 'url': url } unixtime = time.mktime(scheduled_time.timetuple()) mail.send_at = unixtime mail.personalizations[0].dynamic_template_data = dynamic_template_data # mail.personalizations[0].add_to(Email("*****@*****.**")) # mail.personalizations[0].add_substitution(Substitution('event[i].name', 'eat pray love')) # mail.personalizations[0].add_substitution(Substitution('event[i].price', '80')) # mail.personalizations[0].add_substitution(Substitution('event[i].date', '2018-Dec-14')) # mail.personalizations[0].add_substitution(Substitution('event[i].url', 'https://www.eventbrite.com/e/eat-pray-love-tickets-52187209348')) # mail.personalizations[0].add_substitution(Substitution('firstName', 'Bikram')) mail.template_id = "d-c9c69c9a4d164310a1c5f3c289b9d93c" try: sg.client.mail.send.post(request_body=mail.get()) except urllib.HTTPError as e: e.read() exit()
def sender_reset_password(user, host): """ Send the email to the user to reset his password. """ link = f"{host}/user/reset_password/" data = { "code": user.check_code, "link": link, "username": str(user) } mail = Mail() mail.from_email = Email( os.environ.get('FROM_EMAIL'), os.environ.get('FROM_NAME_EMAIL') ) mail.template_id = os.environ.get('ID_TEMPLATE_RESET_PASSWORD') mail.subject = "Réinitialisation de mot de passe." p = Personalization() p.add_to(Email(user.email, str(user))) p.dynamic_template_data = data mail.add_personalization(p) sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) response = sg.client.mail.send.post(request_body=mail.get()) return response
def send_mail(email, contact_name, company_name, telephone): # Create a text/plain message me = '*****@*****.**' you = '*****@*****.**' subject = u'[FRA] Demande de participation ({})'.format(company_name) text = u"""\ Bonjour ! Vous avez recu une nouvelle demande de participation ! Nom du contact: {} Telephone: {} Nom de l'entreprise: {} Email: {} Cordialement, L'equipe Forum. """.format(contact_name, telephone, company_name, email) sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) # Setting from, subject, content, reply to from_email = Email(me) to_email = Email(you) content = Content('text/plain', text) mail = Mail(from_email, subject, to_email, content) # Adding bcc mail.personalizations[0].add_bcc(Email('*****@*****.**')) # Sending email try: sg.client.mail.send.post(request_body=mail.get()) return 'Email sent.' except: return 'Email not sent.'
def test_helloEmail(self): self.maxDiff = None """Minimum required to send an email""" mail = Mail() mail.from_email = Email("*****@*****.**") mail.subject = "Hello World from the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**")) 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>")) self.assertEqual( json.dumps(mail.get(), sort_keys=True), '{"content": [{"type": "text/plain", "value": "some text here"}, ' '{"type": "text/html", ' '"value": "<html><body>some text here</body></html>"}], ' '"from": {"email": "*****@*****.**"}, "personalizations": ' '[{"to": [{"email": "*****@*****.**"}]}], ' '"subject": "Hello World from the SendGrid Python Library"}')
def sendTests(email, assignment, assignment_type, event_list): from_email = Email("*****@*****.**") subject = "{} {}s".format(assignment, assignment_type) to_email = Email(email) content = Content("text/html", "Good Luck!") mail = Mail(from_email, subject, to_email, content) user = User.query.filter_by(email=email).first() mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname.capitalize())) mail.personalizations[0].add_substitution(Substitution("-assignment-", assignment)) mail.personalizations[0].add_substitution(Substitution("-assignment_types-", assignment_type+'s')) eventNum = len(event_list) for c in range(eventNum): mail.personalizations[0].add_substitution(Substitution("-Event{}name-".format(c+1), event_list[c][0])) mail.personalizations[0].add_substitution(Substitution("-Event{}Link-".format(c+1), event_list[c][1])) if eventNum == 1: mail.template_id = "8238dc2b-2da6-4006-90c4-9129416f9bba" elif eventNum == 2: mail.template_id = "21ad7fc8-3183-4a77-8509-bb06973f763f" elif eventNum == 3: mail.template_id = "ad7f080f-bffd-4314-a2ed-da86971b0cfb" elif eventNum == 4: mail.template_id = "19df88b3-25ef-4a16-bf51-519169cf70ab" response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers)
def _build_sg_mail(self, email): mail = Mail() from_name, from_email = rfc822.parseaddr(email.from_email) # Python sendgrid client should improve # sendgrid/helpers/mail/mail.py:164 if not from_name: from_name = None mail.set_from(Email(from_email, from_name)) mail.set_subject(email.subject) personalization = Personalization() for e in email.to: personalization.add_to(Email(e)) for e in email.cc: personalization.add_cc(Email(e)) for e in email.bcc: personalization.add_bcc(Email(e)) personalization.set_subject(email.subject) mail.add_content(Content("text/plain", email.body)) if isinstance(email, EmailMultiAlternatives): for alt in email.alternatives: if alt[1] == "text/html": mail.add_content(Content(alt[1], alt[0])) elif email.content_subtype == "html": mail.contents = [] mail.add_content(Content("text/plain", ' ')) mail.add_content(Content("text/html", email.body)) if hasattr(email, 'categories'): for c in email.categories: mail.add_category(Category(c)) if hasattr(email, 'template_id'): mail.set_template_id(email.template_id) if hasattr(email, 'substitutions'): for k, v in email.substitutions.items(): personalization.add_substitution(Substitution(k, v)) for k, v in email.extra_headers.items(): mail.add_header({k: v}) for attachment in email.attachments: if isinstance(attachment, MIMEBase): attach = Attachment() attach.set_filename(attachment.get_filename()) attach.set_content(base64.b64encode(attachment.get_payload())) mail.add_attachment(attach) elif isinstance(attachment, tuple): attach = Attachment() attach.set_filename(attachment[0]) base64_attachment = base64.b64encode(attachment[1]) if sys.version_info >= (3, ): attach.set_content(str(base64_attachment, 'utf-8')) else: attach.set_content(base64_attachment) attach.set_type(attachment[2]) mail.add_attachment(attach) mail.add_personalization(personalization) return mail.get()
def sendgrid_email(user, recipient, subject, body): sg = sendgrid.SendGridAPIClient(apikey=SendGridAPIKey) from_email = Email(user) to_email = Email(recipient) content = Content("text/plain", body) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def send_email(self, to_email, from_email, subject, body): """Send the email :param to_email: who the email is going to (e.g. 'First Last <*****@*****.**>') :param from_email: who the email is coming from (e.g. 'First Last <*****@*****.**>') :param subject: the email subject line :param body: the email body in HTML format :type to_email: string :type from_email: string :type subject: string :type body: string :returns: HTML status code and JSON message from SendGrid's API :rtype: Integer, JSON """ from_email = Email(from_email) subject = subject to_email = Email(to_email) soup = BeautifulSoup(body, "html.parser") content = Content("text/plain", soup.get_text()) mail = Mail(from_email, subject, to_email, content) response = self.sendgrid.client.mail.send.post(request_body=mail.get()) return response.status_code, response.body
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via sendgrid-python. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text. """ if not current_app.testing: # pragma: no cover try: # Prepare Sendgrid helper objects from sendgrid.helpers.mail import Email, Content, Substitution, Mail from_email = Email(sender_email, sender_name) to_email = Email(recipient) text_content = Content('text/plain', text_message) html_content = Content('text/html', html_message) # Prepare Sendgrid Mail object # Note: RFC 1341: text must be first, followed by html mail = Mail(from_email, subject, to_email, text_content) mail.add_content(html_content) # Send mail via the Sendgrid API response = self.sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) except ImportError: raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE) except Exception as e: print(e) print(e.body) raise
def sendgrid_handler(self, queue_message, to_addrs_to_email_messages_map): self.logger.info( "Sending account:%s policy:%s %s:%s email:%s to %s" % (queue_message.get('account', ''), queue_message['policy']['name'], queue_message['policy']['resource'], str(len(queue_message['resources'])), queue_message['action'].get( 'template', 'default'), to_addrs_to_email_messages_map)) from_email = Email(self.config['from_address']) subject = get_message_subject(queue_message) email_format = queue_message['action'].get('template_format', None) if not email_format: email_format = queue_message['action'].get( 'template', 'default').endswith('html') and 'html' or 'plain' for email_to_addrs, email_content in six.iteritems( to_addrs_to_email_messages_map): for to_address in email_to_addrs: to_email = Email(to_address) content = Content("text/" + email_format, email_content) mail = Mail(from_email, subject, to_email, content) try: self.sendgrid_client.client.mail.send.post( request_body=mail.get()) except (exceptions.UnauthorizedError, exceptions.BadRequestsError) as e: self.logger.warning( "\n**Error \nPolicy:%s \nAccount:%s \nSending to:%s \n\nRequest body:" "\n%s\n\nRequest headers:\n%s\n\n mailer.yml: %s" % (queue_message['policy'], queue_message.get('account', ''), email_to_addrs, e.body, e.headers, self.config)) return False return True
def post(self, request): email = request.data['username'] user = User.objects.get(username=email) profile_id = user.profile.id profile = Profile.objects.get(id=profile_id) profile.password_reset_code = Profile.generate_password_reset_code() profile.save() url = 'https://bquest.ucladevx.com/password' if settings.DEBUG: url = 'http://*****:*****@bquest.ucladevx.com') to_email = Email(email) subject = 'BQuest User Password Reset' reset_link = "{}?code={}&userid={}".format(url, profile.password_reset_code, user.id) content = Content('text/html', 'N/A') mail = Mail(from_email, subject, to_email, content) mail.personalizations[0].add_substitution( Substitution('password_reset_link', reset_link)) mail.template_id = PASSWORD_RESET_TEMPLATE sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) response = sg.client.mail.send.post(request_body=mail.get()) if not (200 <= response.status_code < 300): raise ValidationError( {'sendgrid_status_code': response.status_code}) return HttpResponse(status=200)
def build_email(from_email, subject, to_email, message): """Sent email with Sendgrid""" mail = Mail(from_email=Email(from_email), subject=subject, to_email=Email(to_email), content=Content("text/plain", message)) return mail
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 if not settings.SENDGRID_API_KEY: print('No SendGrid API Key set. Not attempting to send email.') return to_email = _to_email get_or_save_email_subscriber(to_email, 'internal') # setup from_name = str(from_name) subject = str(subject) 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 send_email(email, name): from_email = Email("*****@*****.**") to_email = Email(email) subject = SUBJECT content = Content("text/plain", BODY.format(name)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def send_email(to_email, subject, body, from_email=FROM_EMAIL, html=True): # newlines get wrapped in email, use html body = body.replace('\n', '<br>') # if local no emails if settings.LOCAL: print('local env - no email, only print send_email args:') print('to_email: {}'.format(to_email)) print('subject: {}'.format(subject)) print('body: {}'.format(body)) print('from_email: {}'.format(from_email)) print('html: {}'.format(html)) print() return from_email = Email(from_email) to_email = ADMIN_EMAIL if to_email == ME else to_email to_email = Email(to_email) type_ = html and "text/html" or "text/plain" content = Content(type_, body) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if str(response.status_code)[0] != '2': # TODO logging print('ERROR sending message, status_code {}'.format( response.status_code)) return response
def get_message(self, **kwargs): """ Get message object for email """ config = get_configurations() message = Mail() if "from_email" in kwargs: sender = Email() message_content = kwargs.get("message_content", "") sender.name = kwargs.get("sender", config['SENDGRID']['sender']) sender.email = kwargs.get("from_email", config['SENDGRID']['fromemail']) message.from_email = sender if "subject" in kwargs: message.subject = kwargs.get("subject", "") if "text" in kwargs: content = Content("text/plain", kwargs.get("text", "")) message.add_content(content) if "html" in kwargs: content = Content("text/html", kwargs.get("html", "")) message.add_content(content) if "category" in kwargs: category = Category(kwargs.get("category", "")) message.add_category(category) personalization = self.create_personalization(**kwargs) if personalization: message.add_personalization(personalization) return message.get()
def send_email(self, to_email, subject, content): from_email = Email('*****@*****.**') to_email = Email(to_email) content = Content('text/plain', content) email = Mail(from_email, subject, to_email, content) response = self.sg.client.mail.send.post(request_body=email.get()) return response.status_code, response.body, response.headers
def mail_login_creds(user_profile): if not user_profile.user: username = user_profile.name.split(' ')[0] + str(user_profile.id) password = ''.join(choice(chars) for i in range(8)) user = User.objects.create_user(username=username, password=password) user_profile.user = user user_profile.save() send_to = user_profile.email name = user_profile.name body = email_body.login_creds() body = body % (name, username, password) sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = Email('*****@*****.**') to_email = Email(send_to) subject = "Login Credentials for your account on Alertify app" content = Content('text/html', body) try: mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code % 100 != 2: raise Exception except Exception: user_profile.user = None user_profile.save() user.delete() message = "Error in mailing your login credentials. Please try again." return message message = "Your login credentials have been sent to {0}.".format( send_to) return message
def send_email_using_SendGrid(sender, receiver, mail_subject, mail_content, cc_email=None): message = Mail( from_email=sender, #to_emails = receiver, # Removed since it generates an extra email with SendGrid subject=mail_subject, html_content=mail_content) if cc_email: cc = Email(cc_email) to = Email(receiver) p = Personalization() p.add_to(to) p.add_cc(cc) message.add_personalization(p) else: # no cc to = Email(receiver) p = Personalization() p.add_to(to) message.add_personalization(p) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) return
def send_email( sender=settings.CLOUDCV_TEAM_EMAIL, recipient=None, template_id=None, template_data={}, ): """Function to send email Keyword Arguments: sender {string} -- Email of sender (default: {settings.TEAM_EMAIL}) recipient {string} -- Recipient email address template_id {string} -- Sendgrid template id template_data {dict} -- Dictionary to substitute values in subject and email body """ try: sg = sendgrid.SendGridAPIClient( apikey=os.environ.get("SENDGRID_API_KEY") ) sender = Email(sender) mail = Mail() mail.from_email = sender mail.template_id = template_id to_list = Personalization() to_list.dynamic_template_data = template_data to_email = Email(recipient) to_list.add_to(to_email) mail.add_personalization(to_list) sg.client.mail.send.post(request_body=mail.get()) except Exception: logger.warning( "Cannot make sendgrid call. Please check if SENDGRID_API_KEY is present." ) return
def send(to_email, subject, content): """ Send an email. :param tuple to_email: email recipient address and name :param basestring subject: email subject :param basestring content: email content """ if not get_secret('sendgrid_key'): # This is a test machine return try: if to_email[0].endswith('@gmail.com'): sg = sendgrid.SendGridAPIClient(apikey=get_secret('sendgrid_key')) content = Content('text/plain', content) mail = Mail(Email(*from_email), subject, Email(to_email[0]), content) sg.client.mail.send.post(request_body=mail.get()) else: conn = SMTP('127.0.0.1', 25) mail = Envelope(to_addr=to_email[0], from_addr=from_email, subject=subject, text_body=content) conn.send(mail) except Exception: traceback.print_exc()
def create_ticket_message(ticket): event = ticket.article.event tmpl = loader.get_template('events/email/ticket_message.md') subject = 'Entrada para {}'.format(event.name) body = tmpl.render({ 'ticket': ticket, 'article': ticket.article, 'category': ticket.article.category, 'event': event, }) mail = Mail(from_email=Email(settings.CONTACT_EMAIL, settings.ASSOCIATION_NAME), subject=subject, to_email=Email(ticket.customer_email), content=Content('text/html', as_markdown(body))) attachment = Attachment() pdf_filename = ticket.as_pdf() with open(pdf_filename, 'rb') as f: data = f.read() attachment.content = base64.b64encode(data).decode() attachment.type = 'application/pdf' attachment.filename = 'ticket.pdf' attachment.disposition = 'attachment' mail.add_attachment(attachment) return mail
def _create_email(self, email: dict, email_id: str) -> Mail: self.log_debug('converting email %s to sendgrid format', email_id) mail = Mail() personalization = Personalization() for i, to in enumerate(email.get('to', [])): personalization.add_to(Email(to)) self.log_debug('added to %d to email %s', i, email_id) for i, cc in enumerate(email.get('cc', [])): personalization.add_cc(Email(cc)) self.log_debug('added cc %d to email %s', i, email_id) for i, bcc in enumerate(email.get('bcc', [])): personalization.add_bcc(Email(bcc)) self.log_debug('added bcc %d to email %s', i, email_id) mail.add_personalization(personalization) self.log_debug('added recipients to email %s', email_id) mail.subject = email.get('subject', '(no subject)') self.log_debug('added subject to email %s', email_id) mail.add_content(Content('text/html', email.get('body'))) self.log_debug('added content to email %s', email_id) mail.from_email = Email(email.get('from')) self.log_debug('added from to email %s', email_id) for i, attachment in enumerate(email.get('attachments', [])): mail.add_attachment(self._create_attachment(attachment)) self.log_debug('added attachment %d to email %s', i, email_id) self.log_debug('converted email %s to sendgrid format', email_id) return mail
def test_equality_different_emails(self): address1 = "*****@*****.**" email1 = Email(address1) address2 = "*****@*****.**" email2 = Email(address2) self.assertNotEqual(email1, email2)
def send_email(self, to_email, subject, from_email=None, html=None, text=None, *args, **kwargs): if not any([from_email, self.default_from]): raise ValueError("Missing from email and no default.") if not any([html, text]): raise ValueError("Missing html or text.") self.set_from(Email(from_email or self.default_from)) self.set_subject(subject) personalization = Personalization() if type(to_email) is list: for email in self._extract_emails(to_email): personalization.add_to(email) elif type(to_email) is Email: personalization.add_to(to_email) elif type(to_email) is str: personalization.add_to(Email(to_email)) self.add_personalization(personalization) content = Content("text/html", html) if html else Content("text/plain", text) self.add_content(content) return self.client.mail.send.post(request_body=self.get())
def send_sendgrid(sendgrid_api_key=None, github_email_template=None, github_user_emails=None): assert sendgrid_api_key, "SendGrid API key is required" sg = SendGridAPIClient(apikey=sendgrid_api_key) metadata = github_email_template.metadata from_email = Email(metadata['from']) from_email.name = metadata['from_name'] for ge in github_user_emails: # Add github_user into metadata metadata['user'] = ge # Render content with metadata content = Content("text/html", github_email_template.render_content(metadata)) # Render subject with metadata subject = template_env.from_string(metadata['subject']).render(metadata) to_email = Email(ge.email) mail = Mail(from_email, subject, to_email, content) _body = mail.get() # Add custom args for log fields _custon = {} for key, value in metadata.iteritems(): if key not in ESSENTIAL_FIELDS: _custon[key] = value _custon['repository'] = metadata['repository'] _body['custom_args'] = _custon response = sg.client.mail.send.post(request_body=_body) if response.status_code > 300: # More than 300 means something wrong, do nothing. sys.exit()
def test_empty_obj_add_email(self): email = Email() address = "*****@*****.**" email.email = address self.assertEqual(email.email, address)
def test_add_unicode_name_with_comma(self): email = Email() name = u"Name, Some" email.name = name self.assertEqual(email.name, u'"' + name + u'"')
def test_empty_obj_add_name(self): email = Email() name = "SomeName" email.name = name self.assertEqual(email.name, name)
def test_add_name_with_comma(self): email = Email() name = "Name, Some" email.name = name self.assertEqual(email.name, '"' + name + '"')