Esempio n. 1
0
 def assemble_mail_data(self, headers, body=None):
     message = email.message.Message()
     for key, value in headers.items():
         message.add_header(key, value)
     if body:
         message.set_payload(body)
     return message.as_bytes()
Esempio n. 2
0
    def write_text(self, content, content_type, encoding, file_info):
        content = content.encode(encoding)

        policy = email.policy.compat32.clone(
            linesep='\n',
            max_line_length=0,
            cte_type='8bit',
            raise_on_defect=True)
        message = email.message.Message(policy)

        if file_info.version is not None:
            message.add_header('Version', str(file_info.version))
        if file_info.filetype is not None:
            message.add_header('File-Type', file_info.filetype)

        message.add_header('Checksum', hashlib.md5(content).hexdigest(),
                           type='md5')
        message.add_header('Content-Type', content_type,
                           charset=encoding)
        message.add_header('Content-Length', str(len(content)))

        with open(self.path, 'wb') as fp:
            fp.write(self.MAGIC)
            fp.write(message.as_bytes())
            fp.write(content)
Esempio n. 3
0
def send_mail(email_address, passwd, html_string, code):
    global debug

    if debug:
        url = "http://localhost:5000/verificacion/" + code
    else:
        url = "https://eco-asistente.herokuapp.com/verificacion/" + code

    print(url)
    #Datos de la cuenta.
    gmail_user = '******'
    gmail_password = '******'

    #Instanciación del objeto email.message
    message = email.message.Message()

    #Parámetros para el envío del email.
    sent_from = gmail_user
    to = [email_address]
    message['Subject'] = "EcoAsistente - Activá tu cuenta"

    #Importo el archivo html.

    #Formateo del email.
    message.add_header('Content-Type', 'text/html')
    message.set_payload(html_string)

    #Envío del email.
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to,
                    message.as_string().replace("URL_TO_REPLACE", url))
    server.close()
Esempio n. 4
0
 def get_message_html_plain(self, subject, html_text, plain_text):
     message = email.message.EmailMessage()
     message.add_header('subject', subject)
     message.make_alternative()
     message.add_alternative(html_text, 'html')
     message.add_alternative(plain_text, 'text')
     return message
Esempio n. 5
0
    def write_text(self, content: str, content_type: str, encoding: str,
                   file_info: FileInfo) -> None:
        encoded_content = content.encode(encoding)

        policy = email.policy.compat32.clone(linesep='\n',
                                             max_line_length=0,
                                             cte_type='8bit',
                                             raise_on_defect=True)
        message = email.message.Message(policy)

        if file_info.version is not None:
            message.add_header('Version', str(file_info.version))
        if file_info.filetype is not None:
            message.add_header('File-Type', file_info.filetype)

        message.add_header('Checksum',
                           hashlib.md5(encoded_content).hexdigest(),
                           type='md5')
        message.add_header('Content-Type', content_type, charset=encoding)
        message.add_header('Content-Length', str(len(encoded_content)))

        with open(self.path, 'wb') as fp:
            fp.write(self.MAGIC)
            fp.write(message.as_bytes())
            fp.write(encoded_content)
Esempio n. 6
0
def sendEmail(recipient, content, config, outcome):

  # Create email content
  message = email.message.Message()
  message['Subject'] = 'Your daily COVID-19 report'
  message['From'] = config['address']
  message['To'] = recipient
  message.add_header('Content-Type', 'text/html')
  message.set_payload(content)

  # Start server and log in to sender email
  server = smtplib.SMTP('smtp.gmail.com: 587')
  server.starttls()
  server.login(message['From'], config['password'])

  # Attempt to send email
  try:
    server.sendmail(message['From'], message['To'], message.as_string())
    outcome[0] += 1
  except Exception as e:
    print('Unable to send email to ' + recipient + '. Error: ' + str(e))
    outcome[1] += 1

  # Quit server
  server.quit()
Esempio n. 7
0
def monitor_alert(webpage, notes):
    ### AWS Config ###
    EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = '******'
    EMAIL_PORT = 587

    # Setup email message
    message = email.message.Message()
    message['Subject'] = "Monitor Alert!"
    message['From'] = fromaddr
    message['To'] = ", ".join(toaddr)
    message.add_header('Content-Type', 'text/html')

    # HTML
    template = """\
        <html>
          <head></head>
          <h2>Error Returned On:</h2>
          <body> <h3>%s</h3> <p><b>Notes:</b> <br> %s</p> </body>
        </html>
        """ % (webpage, notes)

    # Add html template as payload, and "stringify" content
    message.set_payload(template)
    msg_full = message.as_string()

    # Send message
    s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
    s.starttls()
    s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    s.sendmail(fromaddr, toaddr, msg_full)
    s.quit()
Esempio n. 8
0
 def test_handle_plain_only(self):
     message = email.message.EmailMessage()
     message.add_header('subject', 'Plain Only')
     plain_content = '<p>HTML tags should be ignored, here.</p>'
     message.set_content(plain_content)
     self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes())
     self.assertExists(models.Contribution, conversation__subject='Plain Only',
                       text__text=plain_content)
Esempio n. 9
0
 def test_html_conversion_simple_list(self):
     message = email.message.EmailMessage()
     message.add_header('subject', 'HTML Only')
     message.make_alternative()
     message.add_alternative('<ul><li>foo</li><li>bar</li></ul></p>', 'html')
     self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes())
     self.assertExists(models.Contribution, conversation__subject='HTML Only',
                       text__text='  * foo\n  * bar')
Esempio n. 10
0
 def test_plain_signature_removal(self):
     message = email.message.EmailMessage()
     message.add_header('subject', 'With Signature')
     plain_content = 'foo\nbar\n-- \nbaz\n-- \nfuz'
     message.set_content(plain_content)
     self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes())
     self.assertExists(models.Contribution, conversation__subject='With Signature',
                       text__text='foo\nbar')
Esempio n. 11
0
    def process(self, baton):
        message = util.dict_get_path(baton, self.message_path)

        for key, value in self.headers.items():
            if key in message:
                message.replace_header(key, value)
            else:
                message.add_header(key, value)

        return baton
Esempio n. 12
0
def weekly_summary_email(summ_set, to_time, from_time):
    ### AWS Config ###
    EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = '******'
    EMAIL_PORT = 587

    # Setup email message
    message = email.message.Message()
    message['Subject'] = 'Weekly Report: %s to %s \n\n' % (from_time, to_time)
    message['From'] = fromaddr
    message['To'] = ", ".join(toaddr)
    message.add_header('Content-Type', 'text/html')

    # HTML
    template = """\
    <html>
        <head></head>
        <h1>Weekly Report:</h1>
        <body>
    """

    for key in summ_set:
        summary_line = """\
            <h3> %s </h3>
            <p>
                <b>Avg Response Time:</b> %s <br>
                <b>Max Response Time:</b> %s <br>
                <b>Total URLs:</b> %s <br>
                <b>Total Errors:</b> %s <br>
                <b>Avg TTFB:</b> %s <br>
                <b>Max TTFB:</b> %s <br>
            </p>
        """ % (key, summ_set[key][0], summ_set[key][1], summ_set[key][2],
               summ_set[key][3], summ_set[key][4], summ_set[key][5])
        # Append single error string to list to join after loop
        template += summary_line

    template_end = """\
        </body>
    </html>
    """

    template = template + template_end

    # Add html template as payload, and "stringify" content
    message.set_payload(template)
    msg_full = message.as_string()

    # Send message
    s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
    s.starttls()
    s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    s.sendmail(fromaddr, toaddr, msg_full)
    s.quit()
Esempio n. 13
0
def send_crawl_summary(domain, error_set):
    ### AWS Config ###
    EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = '******'
    EMAIL_PORT = 587

    # Setup email message
    message = email.message.Message()
    message['Subject'] = "%s Crawl Summary Report" % domain
    message['From'] = fromaddr
    message['To'] = ", ".join(toaddr)
    message.add_header('Content-Type', 'text/html')

    # HTML
    template = """\
    <html>
      <head></head>
      <h1>%s Report:</h1>
      <body>
    """ % domain

    for key in error_set:
        # Concatenates the 'key', (domain page), with the status code, [0], error text, [1], and response time, [2]
        err_line = """\
            <p><h3>%s</h3> <br>
               <b>Status:</b> %s <br>
               <b>Response Time:</b> %s <br>
               <b>Error Message:</b> %s <br>
            </p>
        """ % (key, error_set[key][0], error_set[key][2], error_set[key][1])

        # Append single error string to list to join after loop
        template = template + err_line

    # Join the string list and send it as the error body message
    template_end = """\
        </body>
    </html>
    """

    template = template + template_end

    # Add html template as payload, and "stringify" content
    message.set_payload(template)
    msg_full = message.as_string()

    # Send message
    s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
    s.starttls()
    s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    s.sendmail(fromaddr, toaddr, msg_full)
    s.quit()
Esempio n. 14
0
def sendEmails(emails):

	fromaddr = "*****@*****.**"#'*****@*****.**'
	username = "******"#'*****@*****.**'
	password = "******"#'comoecampina2017'
	server = None

	try:
		server = smtplib.SMTP('smtp.gmail.com:587')
		server.ehlo()
		server.starttls()
		server.login(username,password)
	except Exception as e:
		print "failed to login" + str(e.args) + " " + str(e)

	for data in emails:#["[email protected],David"]:
		userData = data.split(",")
		toaddrs  = userData[0].strip(' \t\n\r')
		#subject = "Nova Versão do Como é Campina?"
		subject = "Alumni Contact - Help in Research"

		# Prepare actual message
		#msg = 'Olá ' + userData[1].strip(' \t\n\r') + ', <br><br>Como está? Primeiramente queríamos te agradecer por sua contribuição em nossa versão anterior do projeto Como é Campina?, aquele mesmo que te pediu para comparar fotos da cidade de Campina Grande. A partir da sua ajuda conseguimos entender melhor a relação entre elementos presentes nas cidades (e.g., como árvores, carros e pessoas nas ruas) e as percepções de segurança e agradabilidade de nossos contribuidores. Com isso, pudemos contribuir para o aperfeiçoamento da maneira como pesquisas de percepção podem utilizar ferramentas de computação como o Como é Campina? <br><br>Em nossa nova versão do projeto, estamos tentando melhorar ainda mais essas ferramentas de modo que automaticamente possamos construir a percepção sobre ruas e, assim, agilizar ainda mais o trabalho de gestores e urbanistas na detecção de problemas e na melhoria das nossas cidades. Para isso <b>precisamos novamente da sua ajuda!</b> <br><br>Basta acessar a URL do projeto https://contribua.org/project/ruascampina/, fazer login com a sua conta (se você não lembrar da sua senha você pode resgatá-la, ou entrar com uma conta sua do Facebook ou Google) e em 5 minutos responder mais algumas comparações de imagens. Sua ajuda é muito importante para nós. Vamos contribuir? <br><br><br> Abraços, <br> Equipe do Como é Campina?'
		msg = 'Hi ' + userData[1].strip(' \t\n\r') + ', <br><br>How are you? My name is David, I\'ve participated in the Study of the United States Institutes for Student Leaders from Brazil in 2009, an US Department of State program, and currently I\'m a Computer Science PhD candidate. <br> <br> I\'ve found your contact through the US programs alumni website and I\'m here to ask you for a help with our research. We\'re studying how computer systems can help in urban planning by capturing and analyzing impressions about images of cities. We\'re asking people to give their impressions about some city images, pointing the scenes that look more pleasant to them. It\'s very important to us to gather opinions from different places and cultures, and your contribution is very important to help us achieve that. <br><br> In 5 minutes you can login in our site (you can use your Facebook or Google account) <br><br> https://contribua.org/project/ruascampina/ <br><br> And answer some images comparison. I would really appreciate your help. <br><br> Thanks in advance! <br><br> David Candeia M Maia - <br> http://www.lsd.ufcg.edu.br/~davidcmm/ <br> http://sites.google.com/site/davidcmmaia/ <br><br> Mestre em Ciência da Computação pela Universidade Federal de Campina Grande<br>Professor do Instituto de Educação, Ciência e Tecnologia do Estado da Paraíba - IFPB<br>Paraíba - Brasil<br><br>MS in Computer Science at Federal University of Campina Grande<br>Professor at Instituto de Educação, Ciência e Tecnologia do Estado da Paraíba - IFPB<br>Paraíba - Brazil'
		#message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
		#""" % (fromaddr, toaddrs, "Nova Versão do Como é Campina?", msg)
		#message = email.message.Message()
		message = MIMEMultipart()
		message['Subject'] = subject
		message['From'] = fromaddr
		message['To'] = toaddrs
		message.add_header('Content-Type','text/html')
		#message.set_payload(msg)
		message.attach(MIMEText(msg, 'html'))

		fp = open("/local/david/pybossa_env/campinaPulse/imagens_divulgacao/avatar.jpg",  'rb')#"/home/davidcmm/workspace_doutorado/campinaPulse/imagens_divulgacao/avatar.jpg", "rb")                                                    
		img = MIMEImage(fp.read())
		fp.close()
		img.add_header('Content-ID', '<{}>'.format("/local/david/pybossa_env/campinaPulse/imagens_divulgacao/avatar.jpg"))
		message.attach(img)

		try:		
			server.sendmail(fromaddr, toaddrs, message.as_string())
			print 'successfully sent the mail to ' + str(toaddrs)
		except Exception as e:
			print "failed to send mail" + str(e.args) + " " + str(e)

	try:
		server.quit()
		server.close()
	except Exception as e:
		print "failed to close " + str(e.args) + " " + str(e)
Esempio n. 15
0
def sendMessage(fromByValue, toByValue, subject, body, headerByName=None):
    'Send a message using SMTP'
    # Prepare
    message = email.message.Message()
    message.add_header(
        'from',
        email.utils.formataddr(
            (fromByValue['nickname'], fromByValue['email'])))
    message.add_header(
        'to',
        email.utils.formataddr((toByValue['nickname'], toByValue['email'])))
    message.add_header('subject', subject)
    message.set_payload(body)
    if headerByName:
        for key, value in headerByName.iteritems():
            message.add_header(key, value)
    # Connect to server
    if fromByValue['smtp'] == 'localhost':
        server = smtplib.SMTP('localhost')
    else:
        server = smtplib.SMTP_SSL(fromByValue['smtp'], 465)
        if len(fromByValue['username']):
            server.login(fromByValue['username'], fromByValue['password'])
    # Send mail
    try:
        server.sendmail(fromByValue['email'], toByValue['email'],
                        message.as_string())
    except socket.error, error:
        raise SMTPError(error)
Esempio n. 16
0
    def get_message(self):
        """
        Assemble the basic message including query parameters.
        """
        message = email.message.Message()
        message['Method'] = self.command
        message['Path'] = self.path

        server_url = parse.SplitResult(
            'http', '{0}:{1}'.format(self.server.server_name,
                                     self.server.server_port), '', '', '')
        request_url = parse.urlsplit(server_url.geturl() + self.path)
        for header, value in parse.parse_qs(request_url.query).items():
            message.add_header(header, value[0])

        return message
Esempio n. 17
0
def main(*args, **kwargs):
    body = kwargs.pop('body', None)

    input_arguments = list(args)
    for key, value in kwargs.items():
        input_arguments += ['--%s' % key, value]

    parser = get_parser()

    args = parser.parse_args(input_arguments)

    relay_host = smtplib.SMTP(args.relay[0], args.relay[1])
    relay_host.set_debuglevel(0)

    if body is None:
        body = sys.stdin.read()

    message = Message()
    for to in args.to or []:
        message.add_header('To', to)
    for cc in args.cc or []:
        message.add_header('Cc', cc)
    if args.from_:
        message.add_header('From', args.from_)

    if args.subject is not None:
        message.subject = args.subject

    message.set_body_text(body, args.encoding)

    for key, value in args.header or []:
        message.add_header(key, value)

    from email.generator import Generator
    policy = email.message.compat32
    g = Generator(
        sys.stdout, maxheaderlen=80, policy=policy, mangle_from_=False)
    try:
        g.flatten(message.message, unixfrom=False)
    except:
        sys.stdout.flush()
        print('')
        raise

    try:
        relay_host.sendmail(
            args.sender, args.recipient, str(message))
    except smtplib.SMTPDataError as e:
        print('Relay returned error on DATA:')
        print(str(e))
    finally:
        try:
            relay_host.quit()
        except smtplib.SMTPServerDisconnected:
            pass
Esempio n. 18
0
def _get_upload_content(field_storage):
  """Returns an email.Message holding the values of the file transfer.

  It decodes the content of the field storage and creates a new email.Message.

  Args:
    field_storage: cgi.FieldStorage that represents uploaded blob.

  Returns:
    An email.message.Message holding the upload information.
  """
  message = email.message.Message()
  message.add_header(
      'content-transfer-encoding',
      field_storage.headers.getheader('Content-Transfer-Encoding', ''))
  message.set_payload(field_storage.file.read())
  payload = message.get_payload(decode=True)
  return email.message_from_string(payload)
Esempio n. 19
0
def _get_upload_content(field_storage):
  """Returns an email.Message holding the values of the file transfer.

  It decodes the content of the field storage and creates a new email.Message.

  Args:
    field_storage: cgi.FieldStorage that represents uploaded blob.

  Returns:
    An email.message.Message holding the upload information.
  """
  message = email.message.Message()
  message.add_header(
      'content-transfer-encoding',
      field_storage.headers.getheader('Content-Transfer-Encoding', ''))
  message.set_payload(field_storage.file.read())
  payload = message.get_payload(decode=True)
  return email.message_from_string(payload)
Esempio n. 20
0
 def compose(cls, from_, to, subject, body, message_id=None):
     message = cls()
     message.add_header('From', from_)
     message.add_header('To', to)
     message.subject = subject
     message.add_header(
         'Date',
         datetime.datetime.utcnow().strftime("%a, %d %b %Y %T +0000"))
     if message_id is None:
         domain = from_.split('@')[1]
         message_id = make_message_id(domain)
     message_id = validate_message_id(message_id)
     message.add_header('Message-ID', message_id)
     message.set_body_text(body, 'utf-8')
     return message
Esempio n. 21
0
    def append(self, content, entry_type, content_type,
               encoding='utf-8', headers=None):
        policy = email.policy.compat32.clone(
            linesep='\n',
            max_line_length=0,
            cte_type='8bit',
            raise_on_defect=True)
        message = email.message.Message(policy)

        content = content.encode(encoding)

        message.add_header('Checksum', hashlib.md5(content).hexdigest(),
                           type='md5')
        message.add_header('Content-Type', content_type, charset=encoding)
        message.add_header('Content-Length', str(len(content)))
        if headers is not None:  # pragma: no branch
            for key, value in headers.items():
                message.add_header(key, str(value))

        super().append(message.as_bytes() + content, entry_type)
Esempio n. 22
0
def _send_message(test_id, part_number, username, password, sender, recipient,
                  headers, subject, body, cls=smtplib.SMTP):
    if settings.SMTP_SERVER_SSL and cls is smtplib.SMTP:
        # Only set the SSL class if the default is not already overridden
        cls = smtplib.SMTP_SSL

    conn = cls(settings.SMTP_SERVER_HOST, settings.SMTP_SERVER_PORT)
    conn.ehlo_or_helo_if_needed()
    if settings.SMTP_SERVER_STARTTLS:
        conn.starttls()
        conn.ehlo_or_helo_if_needed()

    if settings.SMTP_SERVER_HOST not in ('127.0.0.1', 'localhost', '::1'):
        try:
            conn.login(username, password)
        except smtplib.SMTPResponseException:
            CURRENT_TESTS[test_id]['error'] = \
                'Could not authenticate to send message'

    message = email.message.Message()
    message.set_charset('UTF8')
    for header_key, header_value in headers:
        encoded_header_value = str(email.header.Header(header_value, 'UTF8'))
        message.add_header(header_key, encoded_header_value)

    encoded_subject = str(email.header.Header(subject, 'UTF8'))
    encoded_sender = str(email.header.Header(sender, 'UTF8'))
    encoded_recipient = str(email.header.Header(recipient, 'UTF8'))
    message.add_header('Subject', encoded_subject)
    message.add_header('From', encoded_sender)
    message.add_header('To', encoded_recipient)
    message.set_type('text/plain')
    message.set_param('charset', 'UTF8')
    message.set_payload(body, 'UTF8')

    refused = conn.sendmail(sender, [recipient], message.as_string())
    if refused:
        CURRENT_TESTS[test_id]['error'] = 'Recipient refused.'
    conn.quit()
Esempio n. 23
0
def sendMessage(fromByValue, toByValue, subject, body, headerByName=None):
    'Send a message using SMTP'
    # Prepare
    message = email.message.Message()
    message.add_header('from', email.utils.formataddr((fromByValue['nickname'], fromByValue['email'])))
    message.add_header('to', email.utils.formataddr((toByValue['nickname'], toByValue['email'])))
    message.add_header('subject', subject)
    message.set_payload(body)
    if headerByName:
        for key, value in headerByName.iteritems():
            message.add_header(key, value)
    # Connect to server
    if fromByValue['smtp'] == 'localhost':
        server = smtplib.SMTP('localhost')
    else:
        server = smtplib.SMTP_SSL(fromByValue['smtp'], 465)
        if len(fromByValue['username']):
            server.login(fromByValue['username'], fromByValue['password'])
    # Send mail
    try:
        server.sendmail(fromByValue['email'], toByValue['email'], message.as_string())
    except socket.error, error:
        raise SMTPError(error)
Esempio n. 24
0
    def append(self,
               content: str,
               entry_type: bytes,
               content_type: str,
               encoding: str = 'utf-8',
               headers: Optional[Dict[str, Any]] = None) -> None:
        policy = email.policy.compat32.clone(linesep='\n',
                                             max_line_length=0,
                                             cte_type='8bit',
                                             raise_on_defect=True)
        message = email.message.Message(policy)

        encoded_content = content.encode(encoding)

        message.add_header('Checksum',
                           hashlib.md5(encoded_content).hexdigest(),
                           type='md5')
        message.add_header('Content-Type', content_type, charset=encoding)
        message.add_header('Content-Length', str(len(encoded_content)))
        if headers is not None:  # pragma: no branch
            for key, value in headers.items():
                message.add_header(key, str(value))

        self.__file.append(message.as_bytes() + encoded_content, entry_type)
Esempio n. 25
0
smtp.starttls()
smtp.login(smtp_username, smtp_password)

# set variable values
month = (date.today() - timedelta(int(billing_lag))).strftime('%B')
count = 0

# loop in for all results
for (Costs, sn, rg, rg_limit, usagepercentage, emailId, flag) in cursor:

    if sn in exclude_subscriptions:
        logging.info('Skipped ' + rg + ' for subscription ' + sn)
    else:
        # create the email object & html message body
        message = email.message.Message()
        message.add_header('Content-Type', 'text/html')
        message['From'] = sender

        if emailId == 'default':
            recepient = config['email_to_default_address']
            message['To'] = recepient
        else:
            recepient = emailId
            message['To'] = recepient

        message[
            'Subject'] = 'Your usage for resourceGroup {} for month {} is INR {} at is at {} % of your quota'.format(
                rg, month, Costs, usagepercentage)
        #text_message = 'Your usage for month {} is INR {} at is at {} % of your quota'.format(str(date.today),Costs,usagepercentage)
        html_message = '''
        <html>
Esempio n. 26
0
def create(item, codec=Codec):
    """Create an email.message.EmailMessage object using given codec
    """
    message = email.message.EmailMessage()
    identifier = codec.get_id(item)
    issuer = codec.get_issuer(item)
    sender, domain = email.utils.parseaddr(issuer)[1].split("@")
    message.add_header("From", issuer)
    message.add_header("To", codec.get_recipient(item))
    message.add_header("Message-ID", "<{}@{}>".format(uuid.uuid4(), domain))
    message.add_header("References", "<{}@{}>".format(identifier, domain))
    message.add_header("Reply-To", "{}+{}@{}".format(sender, identifier,
                                                     domain))
    message.add_header(
        "Subject",
        "".join(
            "[{}]".format(t)
            for t in [codec.get_human_id(item),
                      codec.get_external_id(item)] if t) + " " +
        codec.get_subject(item),
    )
    context = codec.get_context(item)
    plain = codec.render_template(codec.get_text_template(item), context)
    message.set_content(plain)
    message.add_alternative(
        json.dumps(context).encode("utf-8"), "application", "json")
    message.add_alternative(
        codec.render_template(
            codec.get_html_template(item),
            {
                "markup": codec.text_to_html(plain),
                "context": context
            },
        ),
        "html",
    )
    for file_ in codec.get_attachments(item) or []:
        filename = os.path.basename(file_.name)
        maintype, subtype = mimetypes.guess_type(filename)[0].split("/", 1)
        content = file_.read()
        if maintype == "text":
            charset = "utf-8"
            try:
                content = content.decode(charset)
            except UnicodeDecodeError:
                charset = chardet.detect(content).get("encoding")
                try:
                    content = content.decode(charset)
                except UnicodeDecodeError:
                    maintype, subtype = "application", "octet-stream"
        if maintype == "text":
            message.add_attachment(content,
                                   maintype,
                                   charset=charset,
                                   filename=filename)
        else:
            message.add_attachment(content,
                                   maintype,
                                   subtype,
                                   filename=filename)
    return message
Esempio n. 27
0
import email.message
import mailbox

mail = mailbox.mbox("empty.mbox")
mail.close()
mail = mailbox.mbox("one-message.mbox")
message = email.message.Message()
message.set_payload("a")
message.add_header("h", "v", k="l")
mail.add(message)
mail.close()
Esempio n. 28
0
def add_header(message, header_name, data, list_sep=", "):
    if not data:
        return
    if type(data) is list or type(data) is tuple:
        data = list_sep.join(data)
    message.add_header(header_name, data)