Exemple #1
0
 def send_email(self, workspace, messages):
     '''Send an email according to the settings'''
     
     measurements = workspace.measurements
     assert isinstance(measurements, cpmeas.Measurements)
     
     message = email.message.Message()
     who_from = self.from_address.value
     who_to = [group.recipient.value for group in self.recipients]
     subject = measurements.apply_metadata(self.subject.value)
     
     message["Content-Type"] = "text/plain"
     message["From"] = who_from
     message["To"] = ",".join(who_to)
     message["Subject"] = subject
     
     payload = []
     for msg in messages:
         msg = measurements.apply_metadata(msg)
         payload.append(msg)
     message.set_payload("\n".join(payload))
     
     server = smtplib.SMTP(self.smtp_server.value, self.port.value)
     try:
         server.sendmail(who_from, who_to, message.as_string())
         return message.as_string()
     except:
         logger.error("Failed to send mail", exc_info=True)
         return "Failed to send mail"
Exemple #2
0
 def test_send(self):
     self.mox.StubOutWithMock(mail_request_handler.MailRequestHandler,
                              'dispatcher')
     handler = mail_request_handler.MailRequestHandler(None, None)
     handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)
     handler.dispatcher.add_request(method='POST',
                                    relative_url='URL',
                                    headers=[('Content-Type',
                                              'message/rfc822')],
                                    body='mail message',
                                    source_ip='0.1.0.20')
     message = self.mox.CreateMock(email.message.Message)
     message.as_string().AndReturn('mail message')
     self.mox.ReplayAll()
     handler._send('URL', message)
     self.mox.VerifyAll()
Exemple #3
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)
def forward_mail(ses_recipient, message_id):
    # Retrieve the original message from the S3 bucket.
    message = get_message_from_s3(message_id)

    # Get the complete set of new headers.  This one function is where all the forwarding
    # logic / magic can be contained.
    config = dict(sender=SENDER, recipient=RECIPIENT)
    new_headers = get_new_message_headers(config, ses_recipient, message)

    # Change all the headers now
    set_new_message_headers(message, new_headers)

    # For fault injection (Testing error emails)
    if os.getenv("TEST_LARGE_BODY"):
        logger.info("setting a huge body")
        message.clear_content()
        message.set_content("x" * 20000000)

    if os.getenv("TEST_DEBUG_BODY"):
        logger.info(json.dumps(dict(email_body=message.as_string())))

    # Send the message
    try:
        send_raw_email(message)
    except ClientError as e:
        logger.error("error sending forwarded email", exc_info=True)
        traceback_string = traceback.format_exc()
        error_message = create_error_email(message, traceback_string)
        send_raw_email(error_message)
Exemple #5
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()
Exemple #6
0
    def create(self, subject, from_email, recipients, content, message,
               **kwargs):
        if isinstance(recipients, list):
            recipients = ', '.join(recipients)

        local_file = uuid.uuid4().hex
        local_path = f'{local_file[:2]}/{local_file}'
        local_abs_path = os.path.join(settings.MEDIA_ROOT, 'emails',
                                      local_path)
        local_abs_dir = os.path.dirname(local_abs_path)
        if not os.path.isdir(local_abs_dir):
            pathlib.Path(local_abs_dir).mkdir(parents=True, exist_ok=True)
        with open(local_abs_path, 'w+') as fp:
            fp.write(message.as_string())

        status = kwargs.pop('status', self.model.STATUSES.pending)

        return super().create(
            subject=subject,
            from_email=from_email,
            recipients=recipients,
            content=content,
            status=status,
            local_path=local_path,
            **kwargs,
        )
Exemple #7
0
def sendEmailSMTP(fmail, password, tmail_list, message, append=False):
    """
    :param fmail: 发件账户地址
    :param password: 发件账户密码
    :param tmail_list: 收件人列表
    :param message: 结构化邮件消息
    :param append: 是否将该邮件加入服务器已发送文件夹(默认为否)
    :return mailstate: 发件结果
    """
    mail_host = 'smtp.' + fmail.split('@')[-1]
    #print('ready to send')
    try:
        #print('start try')
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(fmail, password)
        #print('logged')
        smtpObj.sendmail(fmail, tmail_list, message.as_string())
        mailstate = '邮件发送成功\n'
        smtpObj.close()
    except:
        mailstate = '邮件发送失败\n'
    if append:
        imapObj = imaplib.IMAP4_SSL(mail_host)
        imapObj.login(fmail, password)
        imapObj.append('Sent', '\\Recent', 0, message.as_bytes())
        mailstate += '邮件已经加入 已发送 文件夹\n'
        imapObj.logout()
    return mailstate
 def test_send(self):
   self.mox.StubOutWithMock(mail_request_handler.MailRequestHandler,
                            'dispatcher')
   handler = mail_request_handler.MailRequestHandler(None, None)
   handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)
   handler.dispatcher.add_request(
       method='POST',
       relative_url='URL',
       headers=[('Content-Type', 'message/rfc822')],
       body='mail message',
       source_ip='0.1.0.20')
   message = self.mox.CreateMock(email.message.Message)
   message.as_string().AndReturn('mail message')
   self.mox.ReplayAll()
   handler._send('URL', message)
   self.mox.VerifyAll()
Exemple #9
0
def send_email(content, titles):
    # 读取config.json配置发信者信息及收信者信息
    with open('config.json', 'r') as f:
        data = json.load(f)
    mail_host = data['host']
    mail_user = data['user']
    mail_password = data['password']
    sender = data['sender']
    receivers = data['receivers']
    email = []
    for i in range(len(content)):
        message = MIMEText(content[i], 'html', 'utf-8')
        message['From'] = sender
        message['To'] = ','.join(receivers)
        message['Subject'] = titles[i]
        email.append(message)
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(mail_user, mail_password)
        for message in email:
            smtpObj.sendmail(sender, receivers, message.as_string())
            title = message['Subject']
            log(f'[INFO]:推送通知“{title}”成功')
        smtpObj.quit()
    except smtplib.SMTPException as e:
        log(f'[error]:{e}')
Exemple #10
0
def send_email(config, to, message, from_=None, auto_headers=None, _copy=True):
    from_ = from_ or config.email_address
    if not hasattr(to, '__iter__'):
        to = [to]

    if not isinstance(message, email.message.Message):
        ## Probably better to do this for any incoming text:
        message = email.message_from_string(message)

    if auto_headers is None:  ## No info, figure out
        if _copy:
            message = copy.deepcopy(message)
        ## At least make sure there's no newlines in the values:
        _escape_value = lambda s: s.replace('\n', r'\n')

        ## Apparently, this will handle well even a message without headers and '\n\n'
        if not message['to'] and not message['envelope-to']:
            message['To'] = ', '.join(to)
        if not message['from']:
            message['From'] = from_
        ## Subject?..

    message_str = message.as_string()
    smtpcli = get_smtpcli(config)
    log("SMTP sending from %r to %r:    %r", from_, to, message_str)
    res = smtpcli.sendmail(from_, to, message_str)
    log("SMTP close")
    smtpcli.close()
    return message, res
Exemple #11
0
def domain_reactive_email(domain_name):
    ### 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'] = "Domain Back Online"
    message['From'] = fromaddr
    message['To'] = ", ".join(toaddr)
    # message.add_header('Content-Type', 'text/html')

    error_msg = '%s is back online.' % domain_name

    # Add error as payload, and "stringify" content
    message.set_payload(error_msg)
    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()
def send_msg( message, recipients = None ):
	if recipients == None:
		recipients = to_addrs
	log("Sending email to: <%s>" % '> <'.join( recipients ))
	relay = (cfg['relay']['host'], int(cfg['relay']['port']))
	smtp = smtplib.SMTP(relay[0], relay[1])
	smtp.sendmail( from_addr, recipients, message.as_string() )
Exemple #13
0
    def send(self, envelope_sender, envelope_recipients, message):
        """
        Send a message with the given envelope sender and recipients.

        envelope_sender
            Envelope sender address to use

        envelope_recipients
            List of envelope recipient addresses

        message
            Either a byte string or a ``email.message.Message`` object

            If an ``email.message.Message`` object, this will add Message-Id
            and Date headers if not already present.
        """
        if isinstance(message, email.message.Message):

            if 'message-id' not in message:
                message['Message-ID'] = email.utils.make_msgid()

            if 'date' not in message:
                message['Date'] = email.utils.formatdate(localtime=True)

            message = message.as_string()

        errors = self._send_many([(envelope_sender, envelope_recipients,
                                   message)])
        if errors:
            exc = errors[0][0]
            raise exc[0], exc[1], exc[2]
Exemple #14
0
    def send_signup_email(receiver, token):
        
        try:
            SignUp.check_user(receiver)
            port = 465  # For SSL
            sender, password = EMAIL, PASSWORD
            signup_url = SIGNUP_URL + f'/{token}'

            body = f"Dear Sir/Madam,\n\nThis message is sent from Urban Buildings' Earthquake Resistance Assessor(UBERA).\nGo to the URL below to set up your account. The link has a validity of 1 hour.\nPlease access the link within that time.\n\nLink: {signup_url}\n\nBest Regards,\nUBERA Team"
            
            message= email.message.Message()
            message['Subject'] = 'UBERA Registration'
            message['From'] = sender
            message['To'] = receiver
            message.set_payload(body)

            # Create a secure SSL context
            context = ssl.create_default_context()  
            with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
                server.login(sender, password)
                server.sendmail(sender, receiver, message.as_string())
        
        except CustomException as ce:
            print(str(ce))
            raise CustomException(ce)

        except Exception as e:
            print(f"SignUp email not sent due to {str(e)}")
            raise CustomException("500:Mail not sent")
def send_msg(message, recipients=None):
    if recipients == None:
        recipients = to_addrs
    log("Sending email to: <%s>" % "> <".join(recipients))
    relay = (cfg["relay"]["host"], int(cfg["relay"]["port"]))
    smtp = smtplib.SMTP(relay[0], relay[1])
    smtp.sendmail(from_addr, recipients, message.as_string())
Exemple #16
0
 def send_mail(self, recipient):
     message = self.get_mail_messege(recipient)
     context = ssl.create_default_context()
     with smtplib.SMTP_SSL(self.EMAIL_HOST, 465, context=context) as server:
         server.login(self.EMAIL_HOST_USER, self.EMAIL_HOST_PASSWORD)
         server.sendmail(self.EMAIL_HOST_USER, recipient,
                         message.as_string())
Exemple #17
0
def send_msg( message, recipients = None ):
	if recipients == None:
		recipients = to_addrs
	log("Sending email to: <%s>" % '> <'.join( recipients ))
	relay = (cfg['relay']['host'], int(cfg['relay']['port']))
	smtp = smtplib.SMTP(relay[0], relay[1])
	smtp.sendmail( from_addr, recipients, message.as_string() )
Exemple #18
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()
Exemple #19
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()
Exemple #20
0
def forward_mail(ses_recipient, message_id):
    # Retrieve the original message from the S3 bucket.
    message = get_message_from_s3(message_id)

    config = get_runtime_config_dict()
    new_headers = get_new_message_headers(config, ses_recipient, message)

    # Change all the headers now.  Boom, that was easy!
    set_new_message_headers(message, new_headers)

    if os.getenv("TEST_DEBUG_BODY"):
        logger.info(json.dumps(dict(email_body=message.as_string())))

    if os.getenv("TEST_LARGE_BODY"):
        logger.info("setting a huge body, should cause an error")
        message.clear_content()
        message.set_content("x" * 20000000)

    # Send the message
    try:
        send_raw_email(message,
                       envelope_destination=new_headers[X_ENVELOPE_TO])
    except ClientError as e:
        logger.error("error sending forwarded email", exc_info=True)
        traceback_string = traceback.format_exc()
        error_message = create_error_email(message, traceback_string)
        send_raw_email(error_message, envelope_destination=error_message["To"])
Exemple #21
0
def send_raw_email(message, *, envelope_destination):
    client_ses = boto3.client('ses', REGION)
    response = client_ses.send_raw_email(
        Source=message['From'],
        Destinations=[envelope_destination],
        RawMessage={'Data': message.as_string()})
    print("Email sent! MessageId:", response['MessageId'])
Exemple #22
0
def send_msg( message, recipients = None ):
	if recipients == None or len(recipients) < 1:
		emit_log("No recipients found for this message:\n%s" % message)
		return
	emit_log("Sending email to: <%s>\n" % '> <'.join( recipients ))
	relay = (cfg['relay']['host'], int(cfg['relay']['port']))
	smtp = smtplib.SMTP(relay[0], relay[1])
	smtp.sendmail( from_addr, recipients, message.as_string() )
    def send_report(self):
        if self.report == 'never':
            return

        if self.report == 'error' and self._backup_successful():
            return

        if self.email == None or len(self.email) == 0:
            logger.error('{}: Not sending backup report since email configuration is missing or empty'.format(self.name))
            return

        logger.info('{}: Sending backup report to {}'.format(self.name, self.email))

        if self._backup_successful():
            status = 'SUCCESS'
        else:
            status = 'FAILURE'

        timestamp = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat()

        content = []
        content.append('Backup report')
        content.append('')
        content.append('Host: {}'.format(platform.node()))
        content.append('Node: {}'.format(self.name))
        content.append('Date: {}'.format(timestamp))
        content.append('Status: {}'.format(status))

        if args.dry_run:
            content.append('')
            content.append('Backup performed in dry-run mode')
            content.append('No data was stored')

        if len(self.output) > 0:
            content.append('')
            content.append('Output:')
            content += self.output

        content.append('')
        content.append('/Your friendly backup robot')

        message = email.message.EmailMessage()
        message['Subject'] = 'Backup report for {}: {}'.format(self.name, status)
        message['From'] = 'Backup Robot <*****@*****.**>'
        message['To'] = self.email
        message['Reply-To'] = 'Backup Operators <*****@*****.**>'
        message.set_content('\n'.join(content))

        logger.debug('The following message will be sent to {}:'.format(self.email))
        for line in message.as_string().rstrip().split('\n'):
            logger.debug(line)

        try:
            with smtplib.SMTP('localhost') as smtp:
                smtp.send_message(message)
        except:
            logger.error('{}: Sending backup report to {} failed'.format(self.name, self.email))
Exemple #24
0
def send(ses, destination: str, message: MIMEMultipart, source: str = "*****@*****.**") -> None:
    response = ses.send_raw_email(
        Source=source,
        Destinations=[destination],
        RawMessage={"Data": message.as_string()},
    )

    if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
        logging.debug("send_raw_email HTTPStatusCode is not 200! {}".format(response["ResponseMetadata"]["HTTPStatusCode"]))
Exemple #25
0
 def send_message(this,
                  message,
                  smtp_from,
                  smtp_to_list,
                  mail_options=(),
                  rcpt_options=()):
     message_str = message.as_string()
     this.email_sent = True
     self.assertRegex(message_str, message_truth)
Exemple #26
0
def send_msg(message, recipients=None):
    if recipients == None:
        recipients = to_addrs
    if cfg.has_key("default") and cfg["default"].has_key("extra_recipient"):
        recipients.append(cfg["default"]["extra_recipient"])
    log("Sending email to: <%s>" % "> <".join(recipients))
    relay = (cfg["relay"]["host"], int(cfg["relay"]["port"]))
    smtp = smtplib.SMTP(relay[0], relay[1])
    smtp.sendmail(from_addr, recipients, message.as_string())
Exemple #27
0
def send_raw_email(message, *, envelope_destinations):
    client_ses = boto3.client('ses', g_config["region"])
    response = client_ses.send_raw_email(
        Source=message['From'],
        Destinations=envelope_destinations,
        RawMessage=dict(Data=message.as_string()),
    )
    logger.info(
        json.dumps(
            dict(message="message sent", message_id=response['MessageId'])))
def send_msg( message, recipients = None ):
	if recipients == None:
		recipients = to_addrs
	if cfg.has_key('logging') and cfg['logging'].has_key('file'):
		log = open(cfg['logging']['file'], 'a')
		log.write("Sending email to: <%s>\n" % '> <'.join( recipients ))
		log.close()
	relay = (cfg['relay']['host'], int(cfg['relay']['port']))
	smtp = smtplib.SMTP(relay[0], relay[1])
	smtp.sendmail( from_addr, recipients, message.as_string() )
Exemple #29
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()
Exemple #30
0
def send_mail(plan, EMAIL):
    message = MIMEMultipart()
    message["From"] = EMAIL
    message["To"] = EMAIL
    message["Subject"] = "AI_BOT"
    message.attach(MIMEText(plan, "plain"))
    text = message.as_string()
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login("*****@*****.**", os.environ['EMAIL_PASSWORD'])
        server.sendmail("*****@*****.**", EMAIL, text)
Exemple #31
0
def send(fromWho, to, subject, body, server):
    message = email.message.Message()
    message['To'] = to
    message['fromWho'] = fromWho
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    res = server.sendmail(fromWho, to, message.as_string())
    server.quit()

    return res
Exemple #32
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()
Exemple #33
0
def send(fromWho, to, subject, body, server):
  message = email.message.Message()
  message['To'] = to
  message['fromWho'] = fromWho
  message['Subject'] = subject
  message.set_payload(body)

  server = smtplib.SMTP(server)
  res = server.sendmail(fromWho, to, message.as_string())
  server.quit()
  
  return res
def send(sender, to, subject="None", body="None", server="localhost"):
    message = email.message.Message()
    message["To"] = to
    message["From"] = sender
    message["Subject"] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit()
Exemple #35
0
 def send_message(this,
                  message,
                  smtp_from,
                  smtp_to_list,
                  mail_options=(),
                  rcpt_options=()):
     message_str = message.as_string()
     this.email_sent = True
     message_truth = (r'From: .+? <joe@example\.com>\r\n'
                      r'To: .+? <joe@example\.com>\r\n'
                      r'\r\n')
     self.assertRegex(message_str, message_truth)
Exemple #36
0
    def send(self):
        time_send = int(time.time())

        message = MIMEText('%s' % time_send)
        message['From'] = email.utils.formataddr((False, self.sender))
        message['To'] = email.utils.formataddr((False, self.receiver))
        message['Subject'] = self.subject
        message['X-Custom-Tag'] = 'Email-Check-Icinga'

        self.smtpcon.sendmail(self.sender, self.receiver, message.as_string())

        return time_send
Exemple #37
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)
Exemple #38
0
def send(sender, to, subject='None', body='None', server='localhost'):
    """sends a message."""
    message = email.message.Message()
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit()
Exemple #39
0
 def add(self, message, key=None):
     ''' Add a message to the Maildir.
     `message` may be an email.message.Message instance or a path to a file.
 '''
     if isinstance(message, StringTypes):
         return self.save_filepath(message, key=key)
     if isinstance(message, email.message.Message):
         with NamedTemporaryFile('w', dir=os.path.join(self.path,
                                                       'tmp')) as T:
             T.write(message.as_string())
             T.flush()
             key = self.save_filepath(T.name, key=key)
         return key
     raise ValueError("unsupported message type: %s" % (type(message), ))
Exemple #40
0
 def as_mbox(self, fp, keys=None):
     ''' Transcribe the contents of this maildir in UNIX mbox format to the
     file `fp`.
     The optional iterable `keys` designates the messages to transcribe.
     The default is to transcribe all messages.
 '''
     if keys is None:
         keys = self.keys()
     for key in keys:
         with Pfx(key):
             message = self[key]
             text = message.as_string(unixfrom=True)
             fp.write(text)
             fp.write('\n')
Exemple #41
0
def send_by_delivery(delivery, p_from, p_to, message):
    """
    Send `message` email, where `message` is a MIMEText/Message instance created
    by create_message.
    Knows how to handle repoze.sendmail 2.3 differences in `message` arg type.

    """
    try:
        delivery.send(p_from, p_to, message.as_string())
    except AssertionError, e:
        if e.args and e.args[0] == "Message must be instance of email.message.Message":
            delivery.send(p_from, p_to, message)
        else:
            raise
Exemple #42
0
def send_mail(to_addrs, subject, body):
    if not isinstance(to_addrs, (tuple, list)):
        raise TypeError, 'send_mail() expects a tuple or list of recipients'
    if not to_addrs:
        return
    message = email.message.Message()
    message['From'] = admin_email
    for addr in to_addrs:
        message['To'] = addr
    message['Subject'] = subject
    message.set_payload(body)
    s = smtplib.SMTP(mail_host)
    s.sendmail(admin_email, to_addrs, message.as_string())
    s.quit()
    return
def send(
    sender, to,
    subject='None',
    body='None',
    server='localhost'
):
    """sends a message."""
    message = email.message.Message()
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message.set_payload(body)

    server = smtplib.SMTP(server)
    try:
        return server.sendmail(sender, to, message.as_string())
    finally:
        server.quit()
Exemple #44
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()
Exemple #45
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)
Exemple #46
0
    charset = email.charset.Charset('utf-8')
    charset.header_encoding = email.charset.QP
    charset.body_encoding = email.charset.QP

    # Create message-object, fill it and set correct charset.
    message = email.message.Message()
    header = email.header.Header(subject, charset)
    message['To'] = toaddr
    message['From'] = fromaddr
    message['Subject'] = header

    message.set_charset(charset)
    message.set_payload(msg)

    # send mail
    program.communicate(message.as_string())


def get_host_name(ip):
    """Get hostname based on ip-address. Return 'N/A' if not found."""
    hostname = "N/A"

    try:
        hostname = socket.gethostbyaddr(ip)[0]
    except socket.herror:
        pass

    return hostname


#pylint: disable=E1103
Exemple #47
0
def send_mail(fromaddr, toaddrs, message, counter, username, password, host, 
        port, usessl):
    print "args: %s"%repr((fromaddr, toaddrs))
    if options.file:
        f = open(options.file)
        msg = f.read()
        f.close()
        message = email.message_from_string(msg)
        # Update date, some spam filters will not receive email that is 
        # long in the past or far in the future.
        now  = datetime.datetime.utcnow()
        del message['date']
        message['date'] = time.ctime(time.mktime(now.timetuple()))
        print "Date>>>>>>>>>>>>>>" ,message['date']
        msg = message.as_string()
        from_domain = fromaddr.split("@")[-1]
        msgfrom = message['from'].split('@')[0]
        if options.unescape:
            from_domain = from_domain.decode('string_escape')
            msgfrom = msgfrom.decode('string_escape')
        if options.use_smtp_domain:
            from_domain = options.username.split("@")[1]
        fromaddr = msgfrom + "@" + from_domain
    else:
        counter.value += 1
        msgRoot = MIMEMultipart('related')
        if options.subject:
            subject = options.subject
        else:
            subject  = "%d - %s"%(counter.value, toaddrs)
        if options.subject_encoding:
            subject = subject.decode("utf8").encode(options.subject_encoding)
        msgRoot['Subject'] = subject
        msgRoot['From'] = Header(fromaddr,'latin1')
        msgRoot['Reply-To'] = Header(fromaddr,'latin1')
        msgRoot['Sender'] = fromaddr
        msgRoot['To'] = ",".join(map(lambda x: "<%s>"%x, toaddrs))
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        if options.message:
            message = options.message
        if options.content_file:
            f = open(options.content_file)
            message = f.read()
            f.close()
        msgText = MIMEText(message, 'html')
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)
        msgAlternative.attach(msgText)
        msg = msgRoot.as_string()
    if usessl:
        c = smtplib.SMTP_SSL()
    else:
        c = smtplib.SMTP()
        
    c.set_debuglevel(debug)
    c.connect(host,port)
    if gmail:
        c.ehlo()
        c.starttls()
        c.ehlo()
    if options.helo:
        ehlo = options.helo
    else:
        ehlo = fromaddr.split("@")[-1]
    if options.helo_encoding:
        ehlo = ehlo.decode("utf8").encode(options.helo_encoding)
    c.ehlo(ehlo)
    if not (options.no_auth) and (username and password):
        c.login(username,password)
    else:
        print "no-auth is being used"
    smtplib.quoteaddr = lambda x: "<%s>"%x
    if options.set_sender_encoding:
        fromaddr = fromaddr.decode('utf8').encode(options.set_sender_encoding)
    if options.set_recipient_encoding:
        if isinstance(toaddrs, basestring):
            toaddrs = toaddrs.decode("utf8").encode(options.set_recipient_encoding)
        else:
            toaddrs = map(lambda x: x.decode("utf8").encode(options.set_recipient_encoding),toaddrs)
    for i in xrange(int(options.email_per_connection)):
        if options.use_sendmail:
            c.sendmail(fromaddr,toaddrs,msg)
        else:
            print "fromaddr: %s"%repr(fromaddr)
            c.mail(fromaddr)
            if isinstance(toaddrs, basestring):
                toaddrs = [toaddrs]
            print "toaddrs: %s"%toaddrs
            for i in toaddrs:
                c.rcpt(i)
            c.data(msg)
    c.quit()
    print counter.value