Python google.appengine.api.mail.EmailMessage() Examples

The following are code examples for showing how to use google.appengine.api.mail.EmailMessage(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pledgeservice   Author: Lessig2016   File: main.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self):
    data = json.loads(self.request.body)
    ascii_name = data["name"].encode('ascii', errors='ignore')
    ascii_email = data["email"].encode('ascii', errors='ignore')
    ascii_subject = data["subject"].encode('ascii', errors='ignore')
    ascii_body = data["body"].encode('ascii', errors='ignore')

    replyto = '%s <%s>' % (ascii_name, ascii_email)
    message = mail.EmailMessage(sender=('Team Lessig no-reply <[email protected]%s.appspotmail.com>' %
                                        model.Config.get().app_name),
                                reply_to=replyto,
                                subject=ascii_subject)
    message.to = "[email protected]"
    message.body = 'FROM: %s\n\n%s' % (ascii_email, ascii_body)
    message.send()
    util.EnableCors(self)
    self.response.write('Ok.') 
Example 2
Project: python-docs-samples   Author: GoogleCloudPlatform   File: send_message.py    Apache License 2.0 6 votes vote down vote up
def send_approved_mail(sender_address):
    # [START send_message]
    message = mail.EmailMessage(
        sender=sender_address,
        subject="Your account has been approved")

    message.to = "Albert Johnson <[email protected]>"
    message.body = """Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
"""
    message.send()
    # [END send_message] 
Example 3
Project: sndlatr   Author: Schibum   File: models_tests.py    Apache License 2.0 5 votes vote down vote up
def test_remind(self):
        """
        remind should send remind and mark job as done.
        """
        job = self.create_job(state='queued')
        with mock_instance('sndlatr.gmail.Mailman') as mailman:
            mail = mock.create_autospec(spec=gae_mail.EmailMessage)
            mailman.build_reply.return_value = mail
            job.remind('token')
            mailman.send_mail.assert_called_with(mail)
            mailman.build_reply.assert_called_with(job.thread_id_int,
                                                   mock.ANY)
            mailman.quit.assert_called_with()
        job = job.key.get()
        self.assertEquals(job.state, 'done') 
Example 4
Project: sndlatr   Author: Schibum   File: mailnotify.py    Apache License 2.0 5 votes vote down vote up
def _send_failure_notice(job, subject_tpl, tpl_basepath, tpl_vars=None):
    message = mail.EmailMessage(sender=_sender,
                                to=job.user_email,
                                subject=subject_tpl.format(
                                    job.subject))
    localtime = _get_localtime(job)
    ctx = {'scheduled_at': localtime,
           'subject': job.subject}
    if tpl_vars is not None:
        ctx.update(tpl_vars)
    message.body = render_template('{}.txt'.format(tpl_basepath), **ctx)
    message.html = render_template('{}.html'.format(tpl_basepath), **ctx)
    logging.info(u'sending failure notice {} to {}'.format(
        tpl_basepath, job.user_email))
    message.send() 
Example 5
Project: sndlatr   Author: Schibum   File: mailnotify.py    Apache License 2.0 5 votes vote down vote up
def build_remind_message(remind_job):
    """
    Builds a reminder message for given remind_job.
    """
    message = mail.EmailMessage(sender=remind_job.user_email,
                                to=remind_job.user_email)
    ctx = {}
    message.body = render_template('reminder.txt', **ctx)
    message.html = render_template('reminder.html', **ctx)
    return message 
Example 6
Project: sndlatr   Author: Schibum   File: gmail.py    Apache License 2.0 5 votes vote down vote up
def build_reply(self, thread_id, mail=None):
        """
        Modify mail (gae mail.EmailMessage) to a reply of the given thread_id.
        If mail is None, creates a new, empty EmailMessage object.
        This looks up the last message in the given thread and modifies
        the References and Reply-To and subject headers of mail to be a reply
        to this message.
        """
        if mail is None:
            mail = gae_mail.EmailMessage()
        orig_msg = self.get_thread(thread_id, reverse=True, limit=1)
        if not orig_msg:
            raise MailNotFound('thread not found')
        orig_msg = orig_msg[0]

        # set References and In-Reply-To (see rfc rfc2822 3.6.4)
        orig_msg_id = orig_msg.get('rfc_message_id')
        if not orig_msg_id:
            raise RfcMsgIdMissing('Last mail in thread has no rfc message id')
        orig_references = orig_msg.get('references')
        if not orig_references:
            orig_references = orig_msg.get('in_reply_to')
        if not orig_references:
            orig_references = ''

        mail.headers = {'References': orig_references + '\r\n ' + orig_msg_id,
                        'In-Reply-To': orig_msg_id}
        mail.subject = orig_msg['subject']
        return mail 
Example 7
Project: sndlatr   Author: Schibum   File: gmail.py    Apache License 2.0 5 votes vote down vote up
def send_mail(self, mail):
        """ Sends gae mail.EmailMessage via SMTP. """
        smtp = self.open_smtp_session()
        smtp.send_rfc822(mail.to_mime_message())
        self.safe_smtp_quit(smtp) 
Example 8
Project: isthislegit   Author: duo-labs   File: email.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send(self, **kwargs):
        ''' Sends an email using the App Engine Mail API.
        
        Raises an InvalidEmailError if an invalid email address was specified.
        '''
        message = mail.EmailMessage(**kwargs)
        message.send() 
Example 9
Project: flasky-appengine   Author: russomi   File: email.py    MIT License 5 votes vote down vote up
def _send_email_gae(to, subject, template, **kwargs):
    from google.appengine.api import mail

    app = current_app._get_current_object()
    msg = mail.EmailMessage(sender=app.config['FLASKY_MAIL_SENDER'],
                            subject=app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject)
    msg.to = to
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    msg.send() 
Example 10
Project: roger-api   Author: rogertalk   File: api.py    MIT License 5 votes vote down vote up
def post_email(session):
    # Admin only endpoint.
    if not session.account.admin:
        raise errors.UnsupportedEndpoint()
    data = json.loads(flask_extras.get_parameter('data'))
    message = mail.EmailMessage(sender=data['sender'])
    for item in data['items']:
        message.to = item['to']
        message.subject = data['subject'].format(**item['data'])
        message.body = data['text'].format(**item['data'])
        message.html = data['html'].format(**item['data'])
        message.check_initialized()
        message.send()
    return {'success': True} 
Example 11
Project: ctfscoreboard   Author: google   File: mail.py    Apache License 2.0 5 votes vote down vote up
def _send_appengine(message, subject, to, to_name, sender, sender_name):
    """AppEngine mail sender."""
    sender = sender or _appengine_default_sender()
    message = aemail.EmailMessage(
            subject=subject,
            body=message)
    message.to = email.utils.formataddr((to_name, to))
    message.sender = email.utils.formataddr((sender_name, sender))
    app.logger.info('Sending email from: %s, to: %s, subject: %s',
                    message.sender, message.sender, subject)
    try:
        message.send()
    except mail_errors.Error as ex:
        app.logger.exception('Error sending mail: %s', str(ex))
        raise MailFailure('Error sending mail.') 
Example 12
Project: pledgeservice   Author: Lessig2016   File: env.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _send_mail(to, subject, text_body, html_body, reply_to=None):
  """Deferred email task"""
  sender = ('Team Lessig <[email protected]%s.appspotmail.com>' %
            model.Config.get().app_name)
  message = mail.EmailMessage(sender=sender, subject=subject)
  message.to = to
  message.body = text_body
  message.html = html_body
  if reply_to:
    message.reply_to = reply_to
  else:
    message.reply_to = '[email protected]'
  message.send() 
Example 13
Project: python-docs-samples   Author: GoogleCloudPlatform   File: handle_incoming_email_test.py    Apache License 2.0 5 votes vote down vote up
def test_handle_bounced_email(testbed):
    handler = handle_incoming_email.LogSenderHandler()
    handler.request = 'request'
    message = mail.EmailMessage(
        sender='[email protected]',
        subject='Your account has been approved')
    message.to = 'Albert Johnson <[email protected]>'
    message.body = 'Dear Albert.'
    handler.receive(message) 
Example 14
Project: love   Author: Yelp   File: email.py    MIT License 5 votes vote down vote up
def send_appengine_email(sender, recipient, subject, body_html, body_text):
    email = EmailMessage()
    email.sender = sender
    email.to = recipient
    email.subject = subject
    email.body = body_text
    email.html = body_html
    email.send() 
Example 15
Project: server   Author: viur-framework   File: utils.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _GAE_sendEMail(dests, name, skel, extraFiles=[], cc=None, bcc=None, replyTo=None, *args, **kwargs):
	"""
	Internal function for using Google App Engine Email processing API.
	"""
	headers, data = conf["viur.emailRenderer"]( skel, name, dests,**kwargs )

	xheader = {}

	if "references" in headers:
		xheader["References"] = headers["references"]

	if "in-reply-to" in headers:
		xheader["In-Reply-To"] = headers["in-reply-to"]

	if xheader:
		message = mail.EmailMessage(headers=xheader)
	else:
		message = mail.EmailMessage()


	mailfrom = "[email protected]%s.appspotmail.com" % app_identity.get_application_id()

	if "subject" in headers:
		message.subject =  "=?utf-8?B?%s?=" % base64.b64encode( headers["subject"].encode("UTF-8") )
	else:
		message.subject = "No Subject"

	if "from" in headers:
		mailfrom = headers["from"]

	if conf["viur.emailSenderOverride"]:
		mailfrom = conf["viur.emailSenderOverride"]

	if isinstance( dests, list ):
		message.to = ", ".join( dests )
	else:
		message.to = dests

	if cc:
		if isinstance( cc, list ):
			message.cc = ", ".join( cc )
		else:
			message.cc = cc

	if bcc:
		if isinstance( bcc, list ):
			message.bcc = ", ".join( bcc )
		else:
			message.bcc = bcc

	if replyTo:
		message.reply_to = replyTo

	message.sender = mailfrom
	message.html = data.replace("\x00","").encode('ascii', 'xmlcharrefreplace')

	if len( extraFiles )> 0:
		message.attachments = extraFiles
	message.send()
	return True 
Example 16
Project: upvote   Author: google   File: mail_utils.py    Apache License 2.0 4 votes vote down vote up
def Send(subject, body, to=None, cc=None, bcc=None, html=False):
  """Sends an email.

  Args:
    subject: The email subject.
    body: The email body.
    to: The TO address(es). Can be either a string or list of strings, and each
        string can be either a username or email address.
    cc: The CC address(es). Can be either a string or list of strings, and each
        string can be either a username or email address.
    bcc: The BCC address(es). Can be either a string or list of strings, and
        each string can be either a username or email address.
    html: Whether the body contains HTML or plain text.

  Raises:
    NoRecipientsError: if the to, cc, and bcc arguments are all empty.
  """
  message = mail.EmailMessage(
      sender=_SENDER,
      reply_to=_REPLY_TO,
      subject='%s %s' % (_SUBJECT_PREFIX, subject))

  if html:
    message.html = body
  else:
    message.body = body

  to = _SanitizeAddrs(to)
  cc = _SanitizeAddrs(cc)
  bcc = _SanitizeAddrs(bcc)

  if to:
    message.to = to
  if cc:
    message.cc = cc
  if bcc:
    message.bcc = bcc

  # Make sure we're actually sending this to someone.
  recipients = sorted(list(set(to + cc + bcc)))
  if not recipients:
    raise NoRecipientsError

  try:
    logging.info('Sending email to %s', recipients)
    message.check_initialized()
    if env_utils.RunningInProd():
      message.send()

  # If something blows up, log it and move on. Failure to send an email is not
  # something that should take the caller off the rails.
  except Exception:  # pylint: disable=broad-except
    logging.exception('Error encountered while sending email')