Exemple #1
0
def create_message_container(em_from, em_to, em_reply_to):
    """ genereates the dictionary with all the relevant headers
    @param em_from:
    @type em_from:
    @param em_to:
    @type em_to:
    @param em_reply_to:
    @type em_reply_to:
    """
    from_hdr = (utils.formataddr((em_from.name, em_from.email)) if len(em_from.name) > 0 else utils.formataddr(
        (False, em_from.email)))

    reply_to_hdr = (

        utils.formataddr((em_reply_to.name, em_reply_to.email)) if len(em_reply_to.name) > 0 else utils.formataddr(
            (False, em_reply_to.name)))

    to_hdr = (

        utils.formataddr((em_to.name, em_to.email)) if len(em_to.name) > 0 else utils.formataddr((False, em_to.name)))

    from_hdr_charset = determine_encoding(from_hdr)
    reply_to_hdr_charset = determine_encoding(reply_to_hdr)
    to_hdr_charset = determine_encoding(to_hdr)
    # Create message container - This one will house the 'multipart alternative part'
    # and the 'attachments part'.
    mime_mulitpart_mixed = MIMEMultipart("mixed")
    mime_mulitpart_mixed["From"] = Header(from_hdr.encode(from_hdr_charset), from_hdr_charset)
    mime_mulitpart_mixed["To"] = Header(to_hdr.encode(to_hdr_charset), to_hdr_charset)
    mime_mulitpart_mixed["Date"] = Header(utils.formatdate())
    mime_mulitpart_mixed["Reply-To"] = Header(reply_to_hdr.encode(reply_to_hdr_charset), reply_to_hdr_charset)
    mime_mulitpart_mixed["Precedence"] = Header("junk", "US-ASCII")
    mime_mulitpart_mixed["Auto-Submitted"] = Header("auto-generated", "US-ASCII")
    return mime_mulitpart_mixed
Exemple #2
0
def _plain_send_mail(sender, recipient, subject, body):
    header_charset = 'ISO-8859-1'
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    smtp = SMTP(config.get('registration.smtp_host', 'localhost'))
    if config.get('registration.smtp_login'):
        try:
            smtp.starttls()
        except:
            pass
        smtp.login(config.get('registration.smtp_login'), config.get('registration.smtp_passwd'))
    smtp.sendmail(sender, recipient, msg.as_string())
    smtp.quit()
def handler(doc):
    # If all the addresses aren't email addresses, we pass...
    check = [doc['from']] + doc['to'] + doc.get('cc', []) + doc.get('bcc', [])
    for c in check:
        if c[0] != 'email':
            logger.info('skipping %(_id)r - not all email addresses', doc)
            return
    # all addresses are emails - so off we go...
    smtp_items = {}
    m = Message()
    (_, addr) = doc['from']
    smtp_items['smtp_from'] = addr
    m.add_header('From', formataddr((doc['from_display'], doc['from'][1])))

    smtp_to = smtp_items['smtp_to'] = []
    for (_, addr), name in zip(doc.get('to', []), doc.get('to_display', [])):
        m.add_header('To', formataddr((name, addr)))
        smtp_to.append(addr)
    for (_, addr), name in zip(doc.get('cc', []), doc.get('cc_display', [])):
        m.add_header('CC', formataddr((name, addr)))
        smtp_to.append(addr)
    for (_, addr), name in zip(doc.get('bcc', []), doc.get('bcc_display', [])):
        m.add_header('BCC', formataddr((name, addr)))
        smtp_to.append(addr)

    m.add_header("Subject", doc['subject'])
    # for now body is plain-text as-is.
    m.set_payload(doc['body'], 'utf-8')
    attach_info = {'smtp_body': {'data': m.as_string()}}
    emit_schema('rd.msg.outgoing.smtp', smtp_items, attachments=attach_info)
Exemple #4
0
def send_contact_email(host, name, email, site, subject_message, message):
    sender = formataddr((name, email), 'UTF-8')
    receiver = formataddr((site.site_owner, site.site_email), 'UTF-8')
    subject = "Formulário de Contato %s" % host
    text = """\
    Enviado por: "%s" <%s>
    Assunto: %s
    Mensagem:

    %s
    """ % (name, email, subject_message, message)
    html_message = message.replace("\r\n", "<br/>").replace("\n", "<br/>")
    html = """\
    <html>
      <head></head>
      <body>
        <p>Enviado por: "%s" &lt;%s&gt;</p>
        <p>Assunto: %s</p>
        <p>Mensagem:</p>
        <p>%s</p>
      </body>
    </html>
    """ % (name, email, subject_message, html_message)
    attachments = []
    send_email(sender, receiver, subject, text, html, attachments)
Exemple #5
0
def send_single_email(sender, recipient, subject, text, html=None, category=None):
    sender_name, sender_addr = parseaddr(sender)
    from_addr = formataddr((Header(sender_name, CHARSET_UTF8).encode(), sender_addr))
    recipient_name, recipient_addr = parseaddr(recipient)
    to_addr = formataddr((Header(recipient_name, CHARSET_UTF8).encode(), recipient_addr))

    msg = MIMEMultipart('alternative')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject
    if category:
        msg["X-SMTPAPI"] = '{"category" : "%s"}' % category
    part1 = MIMEText(text, 'plain', CHARSET_UTF8)
    msg.attach(part1)
    if html:
        part2 = MIMEText(html, 'html', CHARSET_UTF8)
        msg.attach(part2)
    cfg = config()
    username = cfg.get('email', 'username')
    password = cfg.get('email', 'password')
    log.info('Sending email to recipient: {}'.format(recipient))
    s = smtplib.SMTP(cfg.get('email', 'sp_address'), port=cfg.get('email', 'sp_port'))
    s.login(username, password)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()
Exemple #6
0
def confirmation_mail(reg):
    fields = dict()
    fields.update(reg)
    fields["confirmation_url"] = CONFIRMATION_URL_BASE % reg["id"]
    fields["nick_name"] = reg["nick_name"] or "-"
    fields["university_alt"] = reg["university_alt"] or "-"
    fields["food"] = essen_dict[reg["food"]]
    fields["arbeitskreise"] = reg["arbeitskreise"] or "-"
    fields["notes"] = reg["notes"] or " -\n"
    text = open("MAIL_TEXT.tpl").read().format(**fields)

    # Create a text/plain message
    add_charset("utf-8", QP, QP, "utf-8")
    msg = MIMEText(text, _charset="utf-8")

    msg["Subject"] = "Anmeldung zur ZaPF im SoSe 2013"
    msg["From"] = formataddr((str(Header(ME_NAME, "utf-8")), ME_EMAIL))
    msg["To"] = formataddr((str(Header(reg["first_name"] + " " + reg["last_name"], "utf-8")), reg["email"]))
    msg.add_header("Reply-To", ME_REPLY_TO)

    server = smtplib.SMTP(ME_MAILSERVER)
    server.set_debuglevel(1)

    server.send_message(msg)
    server.quit()
 def _test_cases(self, tokens: List[str], msg_id: int, body: str, email_subject: str,
                 send_as_user: bool, verify_html_body: bool=False,
                 show_message_content: bool=True,
                 verify_body_does_not_include: Optional[List[str]]=None,
                 trigger: str='') -> None:
     othello = self.example_user('othello')
     hamlet = self.example_user('hamlet')
     handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id, 'trigger': trigger}])
     if settings.EMAIL_GATEWAY_PATTERN != "":
         reply_to_addresses = [settings.EMAIL_GATEWAY_PATTERN % (u'mm' + t) for t in tokens]
         reply_to_emails = [formataddr(("Zulip", address)) for address in reply_to_addresses]
     else:
         reply_to_emails = ["noreply@testserver"]
     msg = mail.outbox[0]
     from_email = formataddr(("Zulip missed messages", FromAddress.NOREPLY))
     self.assertEqual(len(mail.outbox), 1)
     if send_as_user:
         from_email = '"%s" <%s>' % (othello.full_name, othello.email)
     self.assertEqual(msg.from_email, from_email)
     self.assertEqual(msg.subject, email_subject)
     self.assertEqual(len(msg.reply_to), 1)
     self.assertIn(msg.reply_to[0], reply_to_emails)
     if verify_html_body:
         self.assertIn(body, self.normalize_string(msg.alternatives[0][0]))
     else:
         self.assertIn(body, self.normalize_string(msg.body))
     if verify_body_does_not_include is not None:
         for text in verify_body_does_not_include:
             self.assertNotIn(text, self.normalize_string(msg.body))
Exemple #8
0
    def test_message_process_model_res_id(self):
        """ Incoming email with ref holding model / res_id but that does not match any message in the thread: must raise since OpenERP saas-3 """
        self.assertRaises(ValueError,
                          self.format_and_process, MAIL_TEMPLATE,
                          email_from=formataddr((self.partner_1.name, self.partner_1.email)),
                          to='*****@*****.**', subject='spam',
                          extra='In-Reply-To: <12321321-openerp-%d-mail.test.simple@%s>' % (self.test_record.id, socket.gethostname()),
                          msg_id='<*****@*****.**>')

        # when 6.1 messages are present, compat mode is available
        # Odoo 10 update: compat mode has been removed and should not work anymore
        self.fake_email.write({'message_id': False})
        # Do: compat mode accepts partial-matching emails
        self.assertRaises(
            ValueError,
            self.format_and_process,
            MAIL_TEMPLATE, email_from=formataddr((self.partner_1.name, self.partner_1.email)),
            msg_id='<*****@*****.**>',
            to='*****@*****.**>', subject='spam',
            extra='In-Reply-To: <12321321-openerp-%d-mail.test.simple@%s>' % (self.test_record.id, socket.gethostname()))

        # 3''. 6.1 compat mode should not work if hostname does not match!
        # Odoo 10 update: compat mode has been removed and should not work anymore and does not depend from hostname
        self.assertRaises(ValueError,
                          self.format_and_process,
                          MAIL_TEMPLATE, email_from=formataddr((self.partner_1.name, self.partner_1.email)),
                          msg_id='<*****@*****.**>',
                          to='*****@*****.**>', subject='spam',
                          extra='In-Reply-To: <*****@*****.**>' % self.test_record.id)

        # Test created messages
        self.assertEqual(len(self.test_record.message_ids), 1)
        self.assertEqual(len(self.test_record.message_ids[0].child_ids), 0)
Exemple #9
0
    def send_html_email(self, to_, from_=None, subject=None, text=None,
                        html=None, charset="utf-8"):

        message = MIMEMultipart("alternative")

        if subject:
            subject_header = Header()
            subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset)
                       if isinstance(subject, str) else subject)
            subject_header.append(subject.strip())
            message["Subject"] = subject_header

        from_ = from_ or self.default_sender
        from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset)
                 if isinstance(from_, str) else from_)
        from_realname, from_addr = parseaddr(from_)
        from_header = Header()
        from_header.append(formataddr((from_realname, from_addr)))
        message['From'] = from_header

        to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset)
               if isinstance(to_, str) else to_)
        to_realname, to_addr = parseaddr(to_)
        to_header = Header()
        to_header.append(formataddr((to_realname, to_addr)))
        message['To'] = to_header

        message.attach(MIMEText(text, "plain", charset))
        message.attach(MIMEText(html, "html", charset))

        self._send(message, from_addr, to_addr)
Exemple #10
0
 def post(self, key):
     email_address = self.request.get('address').strip()
     if not is_email_valid(email_address):
         return 400, {
             'error': 'Email address is not valid.'
         }
     try:
         message_key = ndb.Key(urlsafe=key)
         message = message_key.get()
     except Exception as e:
         logging.exception(e)
         self.abort(404)
     else:
         account = self.get_account()
         message_account_key = message_key.parent()
         if not account or account.key != message_account_key:
             self.abort(403)
         else:
             logging.info('Forwarding message from %s to %s' % (account.email, email_address))
             email_message = mail.EmailMessage(
                 sender=formataddr((message.sender_name, account.email)),
                 to=formataddr((message.receiver_name, email_address)),
                 reply_to=message.reply_to or message.sender_address,
                 subject=message.subject or '',
                 body=message.body,
                 html=message.html,
             )
             email_message.send()
    def test_message_process_alias_followers_bounce(self):
        """ Incoming email from unknown partner / not follower partner on a Followers only alias -> bounce """
        self.alias.write({
            'alias_contact': 'followers',
            'alias_parent_model_id': self.env['ir.model']._get('mail.test.gateway').id,
            'alias_parent_thread_id': self.test_record.id,
        })

        # Test: unknown on followers alias -> bounce
        record = self.format_and_process(MAIL_TEMPLATE, self.email_from, '*****@*****.**', subject='Should Bounce')
        self.assertFalse(record, 'message_process: should have bounced')
        self.assertEqual(len(self._mails), 1,
                         'message_process: incoming email on Followers alias should send a bounce email')
        self.assertEqual(self._mails[0].get('subject'), 'Re: Should Bounce')
        self.assertEqual(self._mails[0].get('email_to')[0], '*****@*****.**')
        self.assertEqual(self._mails[0].get('email_from'), formataddr(('MAILER-DAEMON', '*****@*****.**')))

        # Test: partner on followers alias -> bounce
        self._init_mock_build_email()
        record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, '*****@*****.**', subject='Should Bounce')
        self.assertFalse(record, 'message_process: should have bounced')
        self.assertEqual(len(self._mails), 1,
                         'message_process: incoming email on Followers alias should send a bounce email')
        self.assertEqual(self._mails[0].get('subject'), 'Re: Should Bounce')
        self.assertEqual(self._mails[0].get('email_to')[0], '*****@*****.**')
        self.assertEqual(self._mails[0].get('email_from'), formataddr(('MAILER-DAEMON', '*****@*****.**')))
def MailSenderVocabulary(context):

    items = {}

    # Portal/global E-Mail Address
    portal = api.portal.get()
    items[portal.email_from_address] = formataddr((
        portal.email_from_name,
        portal.email_from_address,
    ))

    # The current authenticated Members E-Mail.
    member = api.user.get_current()
    if member:
        email = member.getProperty("email")
        if email != u"":
            items[email] = formataddr((
                member.getProperty("fullname"),
                email,
            ))

    terms = []
    for _id, title in items.iteritems():
        terms.append(SimpleTerm(
            value=_id,
            token=_id.encode('utf-8'),
            title=title
        ))

    return SimpleVocabulary(terms)
Exemple #13
0
    def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
        """ Return a dictionary for specific email values, depending on a
            partner, or generic to the whole recipients given by mail.email_to.

            :param browse_record mail: mail.mail browse_record
            :param browse_record partner: specific recipient partner
        """
        body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
        subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
        reply_to = self.send_get_mail_reply_to(cr, uid, mail, partner=partner, context=context)
        body_alternative = tools.html2plaintext(body)

        # generate email_to, heuristic:
        # 1. if 'partner' is specified and there is a related document: Followers of 'Doc' <email>
        # 2. if 'partner' is specified, but no related document: Partner Name <email>
        # 3; fallback on mail.email_to that we split to have an email addresses list
        if partner and mail.record_name:
            email_to = [formataddr((_('Followers of %s') % mail.record_name, partner.email))]
        elif partner:
            email_to = [formataddr((partner.name, partner.email))]
        else:
            email_to = tools.email_split(mail.email_to)

        return {
            'body': body,
            'body_alternative': body_alternative,
            'subject': subject,
            'email_to': email_to,
            'reply_to': reply_to,
        }
Exemple #14
0
    def send_email(self,receiver,title,html_obj):
        '''
        所有发送动作为线程安全的
        :param receiver:
        :param title:
        :param html_obj:
        :return:
        '''
        # 邮件头
        EmailHandle.mu.acquire()
        try:
            if not CONF.if_email:return #判断是否需要启动邮件短信模块
            msg = MIMEMultipart('alternative')
            msg['From'] = formataddr((self.user["username"],self.user["email"]))
            msg['To'] = formataddr((self.unicode2str(receiver["username"]),self.unicode2str(receiver["email"])))
            msg['Subject'] = title
            #msg['Cc'] = cc_addr
            # 邮件正文是MIMEText:
            # msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
            # msg.attach(MIMEText(''))
            msg.attach(MIMEText(html_obj,'html','utf-8'))

            # 发送邮件
            
            self.login_server()
            self.server.sendmail(msg['From'], msg['To'], msg.as_string())
            self.server.quit()
            logging.warning("email sender::to "+msg['To']+" success")
            EmailHandle.mu.release()
            return True
        except Exception, e:
            EmailHandle.mu.release()
            logging.warning("email sender::to "+msg['To']+" fail")
            print str(e)
            return False
Exemple #15
0
def createEmailTo(sender_name, sender_email, recipient_name, recipient_email,
                  subject, body, format="plain"):
    """Create an :obj:`email.MIMEText.MIMEtext` instance for an email. This
    method will take care of adding addings a date header and message ID
    to the email, as well as quoting of non-ASCII content.
    """
    if isinstance(body, unicode):
        mail=MIMEText(body.encode("utf-8"), format, "utf-8")
    else:
        mail=MIMEText(body, format)

    if sender_name:
        mail["From"]=emailutils.formataddr((sender_name, sender_email))
    else:
        mail["From"]=sender_email
    if recipient_name:
        mail["To"]=emailutils.formataddr((recipient_name, recipient_email))
    else:
        mail["To"]=recipient_email
    mail["Subject"]=Header(subject.encode("utf-8"), "utf-8")
    mail["Message-Id"]=emailutils.make_msgid()
    mail["Date"]=emailutils.formatdate(localtime=True)
    mail.set_param("charset", "utf-8")

    return mail
Exemple #16
0
def send(debug, header, To, Content, filenames=None):

    header['From'] = formataddr(parseaddr(header['From']))
    To = formataddr(parseaddr(To))

    if filenames:
        msg = multipart.MIMEMultipart()
        # a header mezőit átmásoljuk az üzenetbe
        for field in header:
            msg[field] = header[field]
        msg['To'] = To

        body = text.MIMEText(Content, 'plain', 'utf-8')
        msg.attach(body)

        for filename in filenames:
            msg.attach(attach(filename))

    # Csatolás nélküli szimpla email
    else:
        msg = text.MIMEText(Content, 'plain', 'utf-8')
        for field in header:
            msg[field] = header[field]
        msg['To'] = To

    # Ha csak debug kell, akkor elmentjük a "debug" változóba
    if debug:
        open(debug, 'a').write('From pistike Mon Jan 01 00:00:00 2000\n' + msg.as_string() + '\n')
    # egyébként elküldjük
    else:
        s = smtplib.SMTP('localhost')
        s.sendmail(header['From'], [To], msg.as_string())
        s.quit()
Exemple #17
0
 def _get_default_from(self, cr, uid, context=None):
     this = self.pool.get("res.users").browse(cr, SUPERUSER_ID, uid, context=context)
     if this.alias_name and this.alias_domain:
         return formataddr((this.name, "%s@%s" % (this.alias_name, this.alias_domain)))
     elif this.email:
         return formataddr((this.name, this.email))
     raise UserError(_("Unable to send email, please configure the sender's email address or alias."))
Exemple #18
0
    def send_by_email(self):
        if not self.is_applicant_action:
            raise TypeError(u'{} is not applicant action'.format(self.get_type_display()))
        if not self.branch.collect_obligee_emails:
            # Django silently ignores messages with no recipients
            raise ValueError(u'Action has no recipients')

        sender_name = self.branch.inforequest.applicant_name
        sender_address = self.branch.inforequest.unique_email
        sender_formatted = formataddr((squeeze(sender_name), sender_address))
        recipients = [formataddr(r) for r in self.branch.collect_obligee_emails]

        # FIXME: Attachment name and content type are set by client and not to be trusted. The name
        # must be sanitized and the content type white listed for known content types. Any unknown
        # content type should be replaced with 'application/octet-stream'.

        msg = EmailMessage(self.subject, self.content, sender_formatted, recipients)
        for attachment in self.attachments:
            msg.attach(attachment.name, attachment.content, attachment.content_type)
        msg.send()

        inforequestemail = InforequestEmail(
                inforequest=self.branch.inforequest,
                email=msg.instance,
                type=InforequestEmail.TYPES.APPLICANT_ACTION,
                )
        inforequestemail.save()

        self.email = msg.instance
        self.save(update_fields=[u'email'])
Exemple #19
0
 def _get_default_from(self, cr, uid, context=None):
     this = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
     if this.alias_name and this.alias_domain:
         return formataddr((this.name, '%s@%s' % (this.alias_name, this.alias_domain)))
     elif this.email:
         return formataddr((this.name, this.email))
     raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias."))
Exemple #20
0
    def send_email(self, to_, from_=None, subject=None, body=None,
                   subtype="plain", charset="utf-8"):

        message = MIMEText(body, subtype, charset)

        if subject:
            subject_header = Header()
            subject = (codecs.decode(bytearray(subject, sys.getdefaultencoding()), charset)
                       if isinstance(subject, str) else subject)
            subject_header.append(subject.strip())
            message["Subject"] = subject_header

        from_ = from_ or self.default_sender
        from_ = (codecs.decode(bytearray(from_, sys.getdefaultencoding()), charset)
                 if isinstance(from_, str) else from_)
        from_realname, from_addr = parseaddr(from_)
        from_header = Header()
        from_header.append(formataddr((from_realname, from_addr)))
        message['From'] = from_header

        to_ = (codecs.decode(bytearray(to_, sys.getdefaultencoding()), charset)
               if isinstance(to_, str) else to_)
        to_realname, to_addr = parseaddr(to_)
        to_header = Header()
        to_header.append(formataddr((to_realname, to_addr)))
        message['To'] = to_header

        self._send(message, from_addr, to_addr)
Exemple #21
0
def sendmail(sender, receivers, mail):
    message = MIMEMultipart()
    message['From'] = formataddr((Header(sender['nickname'], 'utf-8').encode(), sender['address']))
    message['To'] = ','.join(map(lambda x: formataddr((Header(x[0], 'utf-8').encode(), x[1])), receivers))
    message['Subject'] = Header(mail['subject'], 'utf-8').encode()

    if 'content' in mail:
        message.attach(MIMEText(mail['content'], 'plain', 'utf-8'))

    if 'content_html' in mail:
        message.attach(MIMEText(mail['content_html'], 'html', 'utf-8'))

    if 'attachments' in mail:
        for attachment in mail['attachments']:
            att = MIMEText(attachment[1], 'base64', 'utf-8')
            att["Content-Type"] = "application/octet-stream"
            att["Content-Disposition"] = 'attachment; filename="{}"'.format(attachment[0])
            message.attach(att)

    if 'images' in mail:
        for image in mail['images']:
            img = MIMEImage(image['data'])
            img.add_header('Content-ID', '<{}>'.format(image['Content-ID']))
            message.attach(img)

    server = smtplib.SMTP_SSL(sender['smtp_server'], sender['smtp_port'])
    server.login(sender['address'], sender['password'])
    server.sendmail(sender['address'], list(zip(*receivers))[1], message.as_string())
    server.quit()
    def get_addresses(self, fields, request, context, from_addr=None, to_addr=None):
        """Return addresses
        """
        pprops = getToolByName(context, 'portal_properties')
        site_props = getToolByName(pprops, 'site_properties')
        portal = getToolByName(context, 'portal_url').getPortalObject()
        pms = getToolByName(context, 'portal_membership')

        # get Reply-To
        reply_addr = None
        if hasattr(self, 'replyto_field'):
            reply_addr = fields.get(self.replyto_field, None)

        # Get From address
        if hasattr(self, 'senderOverride') and self.senderOverride and get_expression(context, self.senderOverride):
            from_addr = get_expression(context, self.senderOverride).strip()
        else:
            from_addr = from_addr or site_props.getProperty('email_from_address') or \
                portal.getProperty('email_from_address')

        # Get To address and full name
        if hasattr(self, 'recipientOverride') and self.recipientOverride and get_expression(context, self.recipientOverride):
            recip_email = get_expression(context, self.recipientOverride)
        else:
            recip_email = None
            if hasattr(self, 'to_field') and self.to_field:
                recip_email = fields.get(self.to_field, None)
            if not recip_email:
                recip_email = self.recipient_email

        recip_email = self._destFormat(recip_email)

        recip_name = self.recipient_name.encode('utf-8')

        # if no to_addr and no recip_email specified, use owner adress if possible.
        # if not, fall back to portal email_from_address.
        # if still no destination, raise an assertion exception.
        if not recip_email and not to_addr:
            ownerinfo = context.getOwner()
            ownerid = ownerinfo.getId()
            fullname = ownerid
            userdest = pms.getMemberById(ownerid)
            if userdest is not None:
                fullname = userdest.getProperty('fullname', ownerid)
            toemail = ''
            if userdest is not None:
                toemail = userdest.getProperty('email', '')
            if not toemail:
                toemail = portal.getProperty('email_from_address')
            assert toemail, """
                    Unable to mail form input because no recipient address has been specified.
                    Please check the recipient settings of the EasyForm "Mailer" within the
                    current form folder.
                """
            to = formataddr((fullname, toemail))
        else:
            to = to_addr or formataddr((recip_name, recip_email))

        return (to, from_addr, reply_addr)
    def send_email(self, sender, recipient, subject, body):
        """
        Send an email
        :param sender: the senders address
        :param recipient: the recipients address
        :param subject: the emails subject
        :param body: the body of the email
        :return: nothing
        """
        # Header class is smart enough to try US-ASCII, then the charset we
        # provide, then fall back to UTF-8.
        header_charset = 'ISO-8859-1'

        # We must choose the body charset manually
        body_charset = None
        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        if body_charset is None:
            log.error("Can not encode body of an email")
            raise Exception("Email body encoding problem for email with subject{}".format(subject))

        # Split real name (which is optional) and email address parts
        sender_name, sender_addr = parseaddr(sender)
        recipient_name, recipient_addr = parseaddr(recipient)

        # We must always pass Unicode strings to Header, otherwise it will
        # use RFC 2047 encoding even on plain ASCII strings.
        sender_name = str(Header(unicode(sender_name), header_charset))
        recipient_name = str(Header(unicode(recipient_name), header_charset))

        # Make sure email addresses do not contain non-ASCII characters
        sender_addr = sender_addr.encode('ascii')
        recipient_addr = recipient_addr.encode('ascii')

        # Create the message ('plain' stands for Content-Type: text/plain)
        msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
        msg['From'] = formataddr((sender_name, sender_addr))
        msg['To'] = formataddr((recipient_name, recipient_addr))
        msg['Subject'] = Header(unicode(subject), header_charset)

        try:
            # Send the message via SMTP to localhost:25
            smtp = SMTP(self._config['email.smtp_server'], port=self._config['email.smtp_port'], timeout=1)
            smtp.sendmail(sender, recipient, msg.as_string())
            smtp.quit()
        except KeyError:
            log.warn("There is no smtp server set in the config file.")
        except timeout:
            log.error("There is smtp timeout error message not sent.")
            log.error("Message was %s" % str(msg))
        except SMTPException, ex:
            log.error("There is smtp error. Message not sent: %s." % str(ex))
            log.error("Message was %s" % str(msg))
Exemple #24
0
    def test_message_process_email_author(self):
        """ Incoming email: recognized author: email_from, author_id, added as follower """
        record = self.format_and_process(MAIL_TEMPLATE, email_from=formataddr((self.partner_1.name, self.partner_1.email)))

        self.assertEqual(record.message_ids[0].author_id, self.partner_1,
                         'message_process: recognized email -> author_id')
        self.assertEqual(record.message_ids[0].email_from, formataddr((self.partner_1.name, self.partner_1.email)))
        self.assertEqual(len(self._mails), 0, 'No notification / bounce should be sent')
Exemple #25
0
def email():
    msg=MIMEText('Hello,马哥! I am JJ','plain','utf-8')
    msg['From'] = formataddr(["JJ",'*****@*****.**'])
    msg['To'] = formataddr(["马哥",'*****@*****.**'])
    msg['Subject']="JJ"
    server = smtplib.SMTP('smtp.126.com',25)
    server.login("*****@*****.**",'pnsuqtpgacrhxzzw')
    server.sendmail("*****@*****.**",["*****@*****.**",],msg.as_string())
    server.quit()
Exemple #26
0
def email(message):
    msg = MIMEText(message, "plain", "utf-8")
    msg["From"] = formataddr(["武沛齐", "*****@*****.**"])
    msg["To"] = formataddr(["走人", "*****@*****.**"])
    msg["Subject"] = "小兵测试"
    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("*****@*****.**", "WW.3945.59")
    server.sendmail("*****@*****.**", ["*****@*****.**"], msg.as_string())
    server.quit()
	def on_message(self,unused_channel,basic_deliver,properties,body):
		
		LOGGER.info('Received message # %s from %s: %s', basic_deliver.delivery_tag,properties.app_id,body)
		#THIS IS WHERE WE MANIPULATE MESSAGES
		#output(body)
		msg = body.split(',')
		if( len(msg)!=3):
			print 'Bad Message'
		else:
			name = msg[0]
			ipaddr = msg[1].split(':')[0].strip()
			port = msg[1].split(':')[1].strip()
			status = msg[2].strip()
			if status == "Online":
				changeNode(name, ipaddr, port)	
			elif status == "Motion":
				LOGGER.info('Motion alert received from name = %s',name)
				archiveTrue(name)
				#send email alert
				#email code is a compilation of examples available online
				#I have modified the contents of the emails to meet the system needs
				if not inRange():
					configFile = open(configName,'r')
					for i in range(3):
					#skip to lines of file needed
						configFile.readline()
					receivers = []
					names = []
					for entry in configFile:
						if entry[0] == '#':
							pass
						else:
							entry = entry.split(',')
							receivers.append(entry[0].strip())
							names.append(entry[1])
					configFile.close()
					msg = MIMEMultipart()
					msg['From'] = formataddr(('SYSTEM ADMINISTRATOR',sender))
					for i in range(len(names)):
						msg['To'] = formataddr((names[i],receivers[i]))
					msg['Subject'] = "MOTION ALERT"
					text = "motion occured at this node: {0}\n".format(name)
					global HostIP
					text = text+"view at: {0}:8080/{1}".format(HostIP,name)
					body = MIMEText(text,'plain')
					msg.attach(body)
					server = smtplib.SMTP('smtp.gmail.com:587')
					server.starttls()
					server.login(senderUserName,senderPassword)
					server.sendmail(sender, receivers, msg.as_string())
					server.quit()
				
			elif status == 'Stop':
				archiveFalse(name)

		self.acknowledge_message(basic_deliver.delivery_tag)
Exemple #28
0
def determine_sender(mail, action='reply'):
    """
    Inspect a given mail to reply/forward/bounce and find the most appropriate
    account to act from and construct a suitable From-Header to use.

    :param mail: the email to inspect
    :type mail: `email.message.Message`
    :param action: intended use case: one of "reply", "forward" or "bounce"
    :type action: str
    """
    assert action in ['reply', 'forward', 'bounce']

    # get accounts
    my_accounts = settings.get_accounts()
    assert my_accounts, 'no accounts set!'

    # extract list of addresses to check for my address
    # X-Envelope-To and Envelope-To are used to store the recipient address
    # if not included in other fields
    # Process the headers in order of importance: if a mail was sent with
    # account X, with account Y in e.g. CC or delivered-to, make sure that
    # account X is the one selected and not account Y.
    candidate_headers = settings.get("reply_account_header_priority")
    for candidate_header in candidate_headers:
        candidate_addresses = getaddresses(mail.get_all(candidate_header, []))

        logging.debug('candidate addresses: %s', candidate_addresses)
        # pick the most important account that has an address in candidates
        # and use that account's realname and the address found here
        for account in my_accounts:
            for seen_name, seen_address in candidate_addresses:
                if account.matches_address(seen_address):
                    if settings.get(action + '_force_realname'):
                        realname = account.realname
                    else:
                        realname = seen_name
                    if settings.get(action + '_force_address'):
                        address = str(account.address)
                    else:
                        address = seen_address

                    logging.debug('using realname: "%s"', realname)
                    logging.debug('using address: %s', address)

                    from_value = formataddr((realname, address))
                    return from_value, account

    # revert to default account if nothing found
    account = my_accounts[0]
    realname = account.realname
    address = account.address
    logging.debug('using realname: "%s"', realname)
    logging.debug('using address: %s', address)

    from_value = formataddr((realname, str(address)))
    return from_value, account
Exemple #29
0
def email(*arg):
    msg = MIMEText(arg[0], 'plain', 'utf-8')
    msg['From'] = formataddr(["帅哥",'*****@*****.**'])
    msg['To'] = formataddr([arg[1],arg[2]])
    msg['Subject'] = arg[3]

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("*****@*****.**", "SHUAIge^^^!")
    server.sendmail('*****@*****.**', ['*****@*****.**',], msg.as_string())
    server.quit()
Exemple #30
0
    def sendmail(self,*args):  #邮箱需要重新定义
        msg = MIMEText(args[0], 'plain', 'utf-8')
        msg['From'] = formataddr(["ICE 监控告警",'*****@*****.**'])
        msg['To'] = formataddr(["用户","运维监控中心"])
        msg['Subject'] = "ICE 监控告警"

        server = smtplib.SMTP("smtp.sina.com", 25)
        server.login("*****@*****.**", "usr/index_usr.jsp")
        server.sendmail('*****@*****.**', ['*****@*****.**',], msg.as_string())
        server.quit()
Exemple #31
0
def send_email_message(message):
    """
    Send an email message.

    On success, returns the message identifier.  Returns None on failure.
    """

    config = get_config()
    server = config.get('email', 'server')
    from_ = config.get('email', 'from')

    # Sort recipients into public ("to") and private ("bcc") lists,
    # unless there is only one recipient, in which case there's no
    # need to hide the address.
    recipients_public = []
    recipients_private = []
    single_recipient = len(message.recipients) == 1
    for recipient in message.recipients:
        if single_recipient or recipient.public:
            recipients_public.append(
                formataddr((recipient.name, recipient.address)))
        else:
            recipients_private.append(
                formataddr((recipient.name, recipient.address)))

    identifier = make_msgid('{}'.format(message.id))

    msg = MIMETextFlowed(message.body)

    msg['Subject'] = Header(message.subject)
    msg['Date'] = formatdate(mktime(message.date.timetuple()))
    msg['From'] = Header(from_)
    msg['To'] = Header(', '.join(recipients_public))
    msg['Message-ID'] = identifier
    if message.thread_identifiers:
        # Currently set this to the last message in the thread,
        # to create a nested thread structure.
        # Alternatively could set "In-Reply-To" to be the first message
        # in the thread to make a thread with a flat structure.
        msg['In-Reply-To'] = Header(message.thread_identifiers[-1])
        msg['References'] = Header(' '.join(message.thread_identifiers))

    with closing(StringIO()) as f:
        Generator(f, mangle_from_=False).flatten(msg)
        msg = f.getvalue()

    try:
        with quitting(SMTP(server)) as smtp:
            refusal = smtp.sendmail(from_,
                                    recipients_public + recipients_private,
                                    msg)

            for (recipient, problem) in refusal.items():
                logger.error('Email message {} refused for {}: {}: {}',
                             message.id, recipient, problem[0], problem[1])

            return identifier

    except SMTPException:
        logger.exception('Email message {} refused for all recipients',
                         message.id)
    except socket.error:
        logger.exception(
            'Email message {} not sent due to failure '
            'to connect to email server', message.id)

    return None
Exemple #32
0
def format_addr(s):
    name, addr = parseaddr(s.decode('utf8'))
    return formataddr(
        (Header(name, 'utf8').encode(),
         addr.encode('utf8') if isinstance(addr, unicode) else addr))
Exemple #33
0
def get_formatted_email(user):
    """get Email Address of user formatted as: `John Doe <*****@*****.**>`"""
    if user == "Administrator":
        return user
    fullname = get_fullname(user)
    return formataddr((fullname, user))
Exemple #34
0
##########利用pandas 模块导入mysql数据
data1 = pd.read_sql(sql1, conn)
data2 = pd.read_sql(sql2, conn)

########把数据写到本地excel,这里写到E盘
writer = pd.ExcelWriter("E:/overdue_data.xlsx")
data1.to_excel(writer, 'Sheet1', index=False)
data2.to_excel(writer, 'Sheet2', index=False)

###关闭所有连接
writer.save()
conn.close()

############################设置一些附属表头参数#############################
msg = MIMEMultipart()
msg['From'] = formataddr(["测试邮件", sender])
msg['To'] = formataddr(["陈芳", receiver1])
msg['To'] = formataddr(["陈芳2", receiver2])

msg['Subject'] = Header(subject, 'utf-8')

msg.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……', 'plain', 'utf-8'))

# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('E:/overdue_data.xlsx', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'

# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="overdue_data.xlsx"'
msg.attach(att1)
Exemple #35
0
 def format_addr(s):
     name, addr = parseaddr(s)
     return formataddr((Header(name, "utf-8").encode(), addr))
Exemple #36
0
    def _send(self,
              auto_commit=False,
              raise_exception=False,
              smtp_session=None):
        IrMailServer = self.env['ir.mail_server']
        for mail_id in self.ids:
            try:
                mail = self.browse(mail_id)
                if mail.state != 'outgoing':
                    if mail.state != 'exception' and mail.auto_delete:
                        mail.sudo().unlink()
                    continue
                # TDE note: remove me when model_id field is present on mail.message - done here to avoid doing it multiple times in the sub method
                if mail.model:
                    model = self.env['ir.model']._get(mail.model)[0]
                else:
                    model = None
                if model:
                    mail = mail.with_context(model_name=model.name)

                # load attachment binary data with a separate read(), as prefetching all
                # `datas` (binary field) could bloat the browse cache, triggerring
                # soft/hard mem limits with temporary data.
                attachments = [(a['datas_fname'], base64.b64decode(a['datas']),
                                a['mimetype'])
                               for a in mail.attachment_ids.sudo().read(
                                   ['datas_fname', 'datas', 'mimetype'])]

                # specific behavior to customize the send email for notified partners
                email_list = []
                if mail.email_to:
                    email_list.append(mail.send_get_email_dict())
                for partner in mail.recipient_ids:
                    email_list.append(
                        mail.send_get_email_dict(partner=partner))

                if mail.cc_visible:
                    email_cc_list = []
                    for partner_cc in mail.recipient_cc_ids:
                        email_to = formataddr(
                            (partner_cc.name or 'False', partner_cc.email
                             or 'False'))
                        email_cc_list.append(email_to)
                    # Convert Email List To String For BCC & CC
                    email_cc_string = ','.join(email_cc_list)
                else:
                    email_cc_string = ''

                if mail.bcc_visible:
                    email_bcc_list = []
                    for partner_bcc in mail.recipient_bcc_ids:
                        email_to = formataddr(
                            (partner_bcc.name or 'False', partner_bcc.email
                             or 'False'))
                        email_bcc_list.append(email_to)
                    # Convert Email List To String For BCC & CC
                    email_bcc_string = ','.join(email_bcc_list)
                else:
                    email_bcc_string = ''

                # headers
                headers = {}
                ICP = self.env['ir.config_parameter'].sudo()
                bounce_alias = ICP.get_param("mail.bounce.alias")
                catchall_domain = ICP.get_param("mail.catchall.domain")
                if bounce_alias and catchall_domain:
                    if mail.model and mail.res_id:
                        headers['Return-Path'] = '%s+%d-%s-%d@%s' % (
                            bounce_alias, mail.id, mail.model, mail.res_id,
                            catchall_domain)
                    else:
                        headers['Return-Path'] = '%s+%d@%s' % (
                            bounce_alias, mail.id, catchall_domain)
                if mail.headers:
                    try:
                        headers.update(safe_eval(mail.headers))
                    except Exception:
                        pass

                # Writing on the mail object may fail (e.g. lock on user) which
                # would trigger a rollback *after* actually sending the email.
                # To avoid sending twice the same email, provoke the failure earlier
                mail.write({
                    'state':
                    'exception',
                    'failure_reason':
                    _('Error without exception. Probably due do sending an email without computed recipients.'
                      ),
                })
                mail_sent = False

                # Update notification in a transient exception state to avoid concurrent
                # update in case an email bounces while sending all emails related to current
                # mail record.
                notifs = self.env['mail.notification'].search([
                    ('is_email', '=', True),
                    ('mail_message_id', 'in',
                     mail.mapped('mail_message_id').ids),
                    ('res_partner_id', 'in', mail.mapped('recipient_ids').ids),
                    ('email_status', 'not in', ('sent', 'canceled'))
                ])
                if notifs:
                    notifs.sudo().write({
                        'email_status': 'exception',
                    })

                # build an RFC2822 email.message.Message object and send it without queuing
                res = None
                for email in email_list:
                    msg = IrMailServer.build_email(
                        email_from=mail.email_from,
                        email_to=email.get('email_to'),
                        subject=mail.subject,
                        body=email.get('body'),
                        body_alternative=email.get('body_alternative'),
                        email_cc=tools.email_split_and_format(email_cc_string),
                        email_bcc=tools.email_split_and_format(
                            email_bcc_string),
                        reply_to=mail.reply_to,
                        attachments=attachments,
                        message_id=mail.message_id,
                        references=mail.references,
                        object_id=mail.res_id
                        and ('%s-%s' % (mail.res_id, mail.model)),
                        subtype='html',
                        subtype_alternative='plain',
                        headers=headers)
                    try:
                        res = IrMailServer.send_email(
                            msg,
                            mail_server_id=mail.mail_server_id.id,
                            smtp_session=smtp_session)
                    except AssertionError as error:
                        if str(error) == IrMailServer.NO_VALID_RECIPIENT:
                            # No valid recipient found for this particular
                            # mail item -> ignore error to avoid blocking
                            # delivery to next recipients, if any. If this is
                            # the only recipient, the mail will show as failed.
                            _logger.info(
                                "Ignoring invalid recipients for mail.mail %s: %s",
                                mail.message_id, email.get('email_to'))
                        else:
                            raise
                if res:
                    mail.write({
                        'state': 'sent',
                        'message_id': res,
                        'failure_reason': False
                    })
                    mail_sent = True

                # /!\ can't use mail.state here, as mail.refresh() will cause an error
                # see revid:[email protected] in 6.1
                if mail_sent:
                    _logger.info(
                        'Mail with ID %r and Message-Id %r successfully sent',
                        mail.id, mail.message_id)
                mail._postprocess_sent_message(mail_sent=mail_sent)
            except MemoryError:
                # prevent catching transient MemoryErrors, bubble up to notify user or abort cron job
                # instead of marking the mail as failed
                _logger.exception(
                    'MemoryError while processing mail with ID %r and Msg-Id %r. Consider raising the --limit-memory-hard startup option',
                    mail.id, mail.message_id)
                raise
            except (psycopg2.Error, smtplib.SMTPServerDisconnected):
                # If an error with the database or SMTP session occurs, chances are that the cursor
                # or SMTP session are unusable, causing further errors when trying to save the state.
                _logger.exception(
                    'Exception while processing mail with ID %r and Msg-Id %r.',
                    mail.id, mail.message_id)
                raise
            except Exception as e:
                failure_reason = tools.ustr(e)
                _logger.exception('failed sending mail (id: %s) due to %s',
                                  mail.id, failure_reason)
                mail.write({
                    'state': 'exception',
                    'failure_reason': failure_reason
                })
                mail._postprocess_sent_message(mail_sent=False)
                if raise_exception:
                    if isinstance(e, AssertionError):
                        # get the args of the original error, wrap into a value and throw a MailDeliveryException
                        # that is an except_orm, with name and value as arguments
                        value = '. '.join(e.args)
                        raise MailDeliveryException(_("Mail Delivery Failed"),
                                                    value)
                    raise

            if auto_commit is True:
                self._cr.commit()
        return True
from email import encoders

sender_email = "*****@*****.**"
sender_name = "Abhishek Singh"
password = "******"

e = pd.read_csv("test_mail.csv")
receiver_emails = e['receiver_emails'].values
receiver_names = e["receiver_names"].values

for receiver_email, receiver_name in zip(receiver_emails, receiver_names):

    print("Sending to " + receiver_name)
    msg = MIMEMultipart()
    msg['Subject'] = 'Advance Testing | ' + receiver_name + ' | Dont Worry !! Dont Panic'
    msg['From'] = formataddr((sender_name, sender_email))
    msg['To'] = formataddr((receiver_name, receiver_email))

    msg.attach(
        MIMEText(
            """<h2>Hello again, """ + receiver_name + """</h2>

                            <p> Hello, 

                            Greetings from Build with LetsUpgrade!!</p>

                          <br>

                            <p>We hope you are doing well during the COVID-19 Pandemic. While the whole nation is on lockdown, we are excited to cheer you up a little.</p>

                          <br>
#   Author :       zongyanzhang
#   date:          2018/12/25

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.header import Header
from smtplib import SMTP
from email.mime.base import MIMEBase
from email.encoders import encode_base64

if __name__ == '__main__':
    msg = MIMEMultipart()
    text = MIMEText('你好!\n不好意思有打扰您!涨工资的事您考虑的怎么样了....', 'plain', 'utf-8')
    msg.attach(text)
    msg['From'] = formataddr((Header('陈云亮',
                                     'utf-8').encode(), '*****@*****.**'))
    msg['To'] = formataddr((Header('领导',
                                   'utf-8').encode(), '*****@*****.**'))
    msg['Subject'] = Header('您在考虑一下', 'utf-8')

    # 添加附件图片
    with open('cool.gif', 'rb') as f:
        mime = MIMEBase('image', 'gif')
        mime.add_header('Content-Disposition',
                        'attachment',
                        filename='cool.gif')
        # 加载图片
        mime.set_payload(f.read())
        # 指定编码格式
        encode_base64(mime)
        msg.attach(mime)
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))
Exemple #40
0
 def _compute_email_formatted(self):
     for partner in self:
         if partner.email:
             partner.email_formatted = formataddr((partner.name or u"False", partner.email or u"False"))
         else:
             partner.email_formatted = ''
Exemple #41
0
# 导入日志框架
from utils.log import logger
"""
email.mime.text.MIMEText (_text[, _subtype[, _charset]]):
MIMENonMultipart中的一个子类,创建包含文本数据的邮件体,_text 是包含消息负载的字符串,_subtype 指定文本类型,
支持 plain(默认值)或 html类型的字符串。_charset设置字符集,参数接受一个charset实例。
"""
with open('mailfile', 'rb') as fp:  #读取文件内容
    msg = MIMEText(fp.read(), 'plain', 'utf-8')  #创建消息对象
logger.debug('读取的消息为:{}'.format(msg))

HOST = "mail.woniuxy.com"  # 定义smtp主机
TO = "*****@*****.**"  # 定义邮件收件人
FROM = "*****@*****.**"  # 定义邮件发件人
PASSWD = "Student123"  # 定义邮件发送人密码

msg['Subject'] = "测试通过Python发送邮件"
msg['From'] = formataddr(["学生", "*****@*****.**"])
msg['To'] = formataddr(["徐林林", "*****@*****.**"])

# if __name__ == '__main__':
# try:
#     server = smtplib.SMTP() # 创建一个 SMTP() 对象
#     server.connect(HOST,"25") # 通过 connect 方法连接 smtp 主机
#     #server.starttls() # 启动安全传输模式
#     server.login(FROM,PASSWD) # 邮箱账号登录校验
#     server.sendmail(FROM,TO, msg.as_string()) # 邮件发送
#     server.quit() # 断开 smtp 连接
#     print("邮件发送成功!")
# except Exception as e:
#     print('失败:'+str(e))
Exemple #42
0
 def _get_default_from(self):
     if self.env.user.email:
         return formataddr((self.env.user.name, self.env.user.email))
     raise UserError(
         _("Unable to send email, please configure the sender's email address."
           ))
Exemple #43
0
# coding:utf-8

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.utils import formataddr

sender = '********'@163.com'
receivers = '********'@qq.com'  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEMultipart()
message['From'] = formataddr(["来自简书作者的问候", sender])  # 发送者
message['To'] = formataddr(["来自简书作者董小贱的问候", receivers])  # 接收者

subject = '这是一封正常正常邮件, 并不是异常的!'
message['Subject'] = Header(subject, 'utf-8')

message.attach(MIMEText('这是邮件的正文内容', 'plain', 'utf-8 '))  # 邮件的正文内容
att1 = MIMEText(open('dongxiaojian.txt').read(), 'base64', 'utf-8')  # 构建邮件附件
att1["Content-Disposition"] = 'attachment;filename="dongxiaojian.txt"'  # 这里的filename就是收到附件的名字
message.attach(att1)

# 以附件的形式添加图片
f = open('timg.jpeg', 'rb')
att2 = MIMEImage(f.read())
f.close()
att2["Content-Disposition"] = 'attachment;filename="danding.jpeg"'  # 这里的filename就是收到附件图片的的名字
message.attach(att2)
Exemple #44
0
 def _compute_email_formatted(self):
     for partner in self:
         partner.email_formatted = formataddr((partner.name, partner.email))
Exemple #45
0
def _format_addr(name, addr):
    return formataddr((Header(name, 'utf-8').encode(), addr))
Exemple #46
0
from email.utils import formataddr
portal = context.getPortalObject()
event = portal.restrictedTraverse(event_relative_url)

subject = event.getTitle()
body = event.getTextContent()
sender = event.getSourceValue()
if kw.get("from_url") is not None:
    from_url = kw.get("from_url")
elif sender is not None:
    from_url = formataddr(
        (sender.hasTitle()
         and sender.getTitle(), sender.getDefaultEmailText()))
else:
    from_url = portal.portal_preferences.getPreferredEventSenderEmail()

to_url = formataddr((context.hasTitle()
                     and context.getTitle(), context.getDefaultEmailText()))

document_type_list = list(event.getPortalEmbeddedDocumentTypeList()) + list(
    event.getPortalDocumentTypeList())
embedded_file_list = event.getAggregateValueList(
    portal_type=document_type_list)

extra_header_dict = kw.get('extra_header_dict') or {}

content_type = event.getContentType()
mail_message = portal.Base_createMailMessageAsString(
    from_url,
    to_url,
    subject,
Exemple #47
0
def get_formatted_email(user):
    """get Email Address of user formatted as: `John Doe <*****@*****.**>`"""
    fullname = get_fullname(user)
    mail = get_email_address(user)
    return formataddr((fullname, mail))
Exemple #48
0
def build_email(
    template_prefix: str,
    to_user_ids: Optional[List[int]] = None,
    to_emails: Optional[List[str]] = None,
    from_name: Optional[str] = None,
    from_address: Optional[str] = None,
    reply_to_email: Optional[str] = None,
    language: Optional[str] = None,
    context: Mapping[str, Any] = {},
    realm: Optional[Realm] = None,
) -> EmailMultiAlternatives:
    # Callers should pass exactly one of to_user_id and to_email.
    assert (to_user_ids is None) ^ (to_emails is None)
    if to_user_ids is not None:
        to_users = [
            get_user_profile_by_id(to_user_id) for to_user_id in to_user_ids
        ]
        if realm is None:
            assert len({to_user.realm_id for to_user in to_users}) == 1
            realm = to_users[0].realm
        to_emails = [
            str(
                Address(display_name=to_user.full_name,
                        addr_spec=to_user.delivery_email))
            for to_user in to_users
        ]

    extra_headers = {}
    if realm is not None:
        # formaddr is meant for formatting (display_name, email_address) pair for headers like "To",
        # but we can use its utility for formatting the List-Id header, as it follows the same format,
        # except having just a domain instead of an email address.
        extra_headers["List-Id"] = formataddr((realm.name, realm.host))

    context = {
        **context,
        "support_email": FromAddress.SUPPORT,
        "email_images_base_uri":
        settings.ROOT_DOMAIN_URI + "/static/images/emails",
        "physical_address": settings.PHYSICAL_ADDRESS,
    }

    def render_templates() -> Tuple[str, str, str]:
        email_subject = (loader.render_to_string(
            template_prefix + ".subject.txt",
            context=context,
            using="Jinja2_plaintext").strip().replace("\n", ""))
        message = loader.render_to_string(template_prefix + ".txt",
                                          context=context,
                                          using="Jinja2_plaintext")

        try:
            html_message = loader.render_to_string(template_prefix + ".html",
                                                   context)
        except TemplateDoesNotExist:
            emails_dir = os.path.dirname(template_prefix)
            template = os.path.basename(template_prefix)
            compiled_template_prefix = os.path.join(emails_dir, "compiled",
                                                    template)
            html_message = loader.render_to_string(
                compiled_template_prefix + ".html", context)
        return (html_message, message, email_subject)

    # The i18n story for emails is a bit complicated.  For emails
    # going to a single user, we want to use the language that user
    # has configured for their Zulip account.  For emails going to
    # multiple users or to email addresses without a known Zulip
    # account (E.g. invitations), we want to use the default language
    # configured for the Zulip organization.
    #
    # See our i18n documentation for some high-level details:
    # https://zulip.readthedocs.io/en/latest/translating/internationalization.html

    if not language and to_user_ids is not None:
        language = to_users[0].default_language
    if language:
        with override_language(language):
            # Make sure that we render the email using the target's native language
            (html_message, message, email_subject) = render_templates()
    else:
        (html_message, message, email_subject) = render_templates()
        logger.warning("Missing language for email template '%s'",
                       template_prefix)

    if from_name is None:
        from_name = "Zulip"
    if from_address is None:
        from_address = FromAddress.NOREPLY
    if from_address == FromAddress.tokenized_no_reply_placeholder:
        from_address = FromAddress.tokenized_no_reply_address()
    if from_address == FromAddress.no_reply_placeholder:
        from_address = FromAddress.NOREPLY
    if from_address == FromAddress.support_placeholder:
        from_address = FromAddress.SUPPORT

    # Set the "From" that is displayed separately from the envelope-from.
    extra_headers["From"] = str(
        Address(display_name=from_name, addr_spec=from_address))
    # Check ASCII encoding length.  Amazon SES rejects emails with
    # From names longer than 320 characters (which appears to be a
    # misinterpretation of the RFC); in that case we drop the name
    # from the From line, under the theory that it's better to send
    # the email with a simplified From field than not.
    if len(sanitize_address(extra_headers["From"], "utf-8")) > 320:
        extra_headers["From"] = str(Address(addr_spec=from_address))

    # If we have an unsubscribe link for this email, configure it for
    # "Unsubscribe" buttons in email clients via the List-Unsubscribe header.
    #
    # Note that Microsoft ignores URLs in List-Unsubscribe headers, as
    # they only support the alternative `mailto:` format, which we
    # have not implemented.
    if "unsubscribe_link" in context:
        extra_headers["List-Unsubscribe"] = f"<{context['unsubscribe_link']}>"
        extra_headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click"

    reply_to = None
    if reply_to_email is not None:
        reply_to = [reply_to_email]
    # Remove the from_name in the reply-to for noreply emails, so that users
    # see "noreply@..." rather than "Zulip" or whatever the from_name is
    # when they reply in their email client.
    elif from_address == FromAddress.NOREPLY:
        reply_to = [FromAddress.NOREPLY]

    envelope_from = FromAddress.NOREPLY
    mail = EmailMultiAlternatives(email_subject,
                                  message,
                                  envelope_from,
                                  to_emails,
                                  reply_to=reply_to,
                                  headers=extra_headers)
    if html_message is not None:
        mail.attach_alternative(html_message, "text/html")
    return mail
Exemple #49
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            username=dict(type='str'),
            password=dict(type='str', no_log=True),
            host=dict(type='str', default='localhost'),
            port=dict(type='int', default=25),
            sender=dict(type='str', default='root', aliases=['from']),
            to=dict(type='list', default=['root'], aliases=['recipients']),
            cc=dict(type='list', default=[]),
            bcc=dict(type='list', default=[]),
            subject=dict(type='str', required=True, aliases=['msg']),
            body=dict(type='str'),
            attach=dict(type='list', default=[]),
            headers=dict(type='list', default=[]),
            charset=dict(type='str', default='utf-8'),
            subtype=dict(type='str', default='plain', choices=['html', 'plain']),
            secure=dict(type='str', default='try', choices=['always', 'never', 'starttls', 'try']),
            timeout=dict(type='int', default=20),
        ),
        required_together=[['password', 'username']],
    )

    username = module.params.get('username')
    password = module.params.get('password')
    host = module.params.get('host')
    port = module.params.get('port')
    sender = module.params.get('sender')
    recipients = module.params.get('to')
    copies = module.params.get('cc')
    blindcopies = module.params.get('bcc')
    subject = module.params.get('subject')
    body = module.params.get('body')
    attach_files = module.params.get('attach')
    headers = module.params.get('headers')
    charset = module.params.get('charset')
    subtype = module.params.get('subtype')
    secure = module.params.get('secure')
    timeout = module.params.get('timeout')

    code = 0
    secure_state = False
    sender_phrase, sender_addr = parseaddr(sender)

    if not body:
        body = subject

    try:
        if secure != 'never':
            try:
                if PY3:
                    smtp = smtplib.SMTP_SSL(host=host, port=port, timeout=timeout)
                else:
                    smtp = smtplib.SMTP_SSL(timeout=timeout)
                code, smtpmessage = smtp.connect(host, port)
                secure_state = True
            except ssl.SSLError as e:
                if secure == 'always':
                    module.fail_json(rc=1, msg='Unable to start an encrypted session to %s:%s: %s' %
                                               (host, port, to_native(e)), exception=traceback.format_exc())
            except Exception:
                pass

        if not secure_state:
            if PY3:
                smtp = smtplib.SMTP(host=host, port=port, timeout=timeout)
            else:
                smtp = smtplib.SMTP(timeout=timeout)
            code, smtpmessage = smtp.connect(host, port)

    except smtplib.SMTPException as e:
        module.fail_json(rc=1, msg='Unable to Connect %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())

    try:
        smtp.ehlo()
    except smtplib.SMTPException as e:
        module.fail_json(rc=1, msg='Helo failed for host %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())

    if int(code) > 0:
        if not secure_state and secure in ('starttls', 'try'):
            if smtp.has_extn('STARTTLS'):
                try:
                    smtp.starttls()
                    secure_state = True
                except smtplib.SMTPException as e:
                    module.fail_json(rc=1, msg='Unable to start an encrypted session to %s:%s: %s' %
                                     (host, port, to_native(e)), exception=traceback.format_exc())
                try:
                    smtp.ehlo()
                except smtplib.SMTPException as e:
                    module.fail_json(rc=1, msg='Helo failed for host %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())
            else:
                if secure == 'starttls':
                    module.fail_json(rc=1, msg='StartTLS is not offered on server %s:%s' % (host, port))

    if username and password:
        if smtp.has_extn('AUTH'):
            try:
                smtp.login(username, password)
            except smtplib.SMTPAuthenticationError:
                module.fail_json(rc=1, msg='Authentication to %s:%s failed, please check your username and/or password' % (host, port))
            except smtplib.SMTPException:
                module.fail_json(rc=1, msg='No Suitable authentication method was found on %s:%s' % (host, port))
        else:
            module.fail_json(rc=1, msg="No Authentication on the server at %s:%s" % (host, port))

    if not secure_state and (username and password):
        module.warn('Username and Password was sent without encryption')

    msg = MIMEMultipart(_charset=charset)
    msg['From'] = formataddr((sender_phrase, sender_addr))
    msg['Subject'] = Header(subject, charset)
    msg.preamble = "Multipart message"

    for header in headers:
        # NOTE: Backward compatible with old syntax using '|' as delimiter
        for hdr in [x.strip() for x in header.split('|')]:
            try:
                h_key, h_val = hdr.split('=')
                h_val = to_native(Header(h_val, charset))
                msg.add_header(h_key, h_val)
            except Exception:
                module.warn("Skipping header '%s', unable to parse" % hdr)

    if 'X-Mailer' not in msg:
        msg.add_header('X-Mailer', 'Ansible mail module')

    addr_list = []
    for addr in [x.strip() for x in blindcopies]:
        addr_list.append(parseaddr(addr)[1])    # address only, w/o phrase

    to_list = []
    for addr in [x.strip() for x in recipients]:
        to_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])    # address only, w/o phrase
    msg['To'] = ", ".join(to_list)

    cc_list = []
    for addr in [x.strip() for x in copies]:
        cc_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])    # address only, w/o phrase
    msg['Cc'] = ", ".join(cc_list)

    part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset)
    msg.attach(part)

    # NOTE: Backware compatibility with old syntax using space as delimiter is not retained
    #       This breaks files with spaces in it :-(
    for filename in attach_files:
        try:
            part = MIMEBase('application', 'octet-stream')
            with open(filename, 'rb') as fp:
                part.set_payload(fp.read())
            encoders.encode_base64(part)
            part.add_header('Content-disposition', 'attachment', filename=os.path.basename(filename))
            msg.attach(part)
        except Exception as e:
            module.fail_json(rc=1, msg="Failed to send mail: can't attach file %s: %s" %
                             (filename, to_native(e)), exception=traceback.format_exc())

    composed = msg.as_string()

    try:
        result = smtp.sendmail(sender_addr, set(addr_list), composed)
    except Exception as e:
        module.fail_json(rc=1, msg="Failed to send mail to '%s': %s" %
                         (", ".join(set(addr_list)), to_native(e)), exception=traceback.format_exc())

    smtp.quit()

    if result:
        for key in result:
            module.warn("Failed to send mail to '%s': %s %s" % (key, result[key][0], result[key][1]))
        module.exit_json(msg='Failed to send mail to at least one recipient', result=result)

    module.exit_json(msg='Mail sent successfully', result=result)
Exemple #50
0
def send_email(plaintext_msg, message_html, recipient, subject):

    # the message_html that was passed is everything *inside* the body tags
    # add the email signature, html + body tag

    html_template = '''
    <html>
    <body>
        %s

        <p>- qBRC Team</p>

        <div style="font-size: 12px; margin-top: 20px;">
        Quantitative Biomedical Research Center (qBRC)<br>
        Dept. of Biostatistics | Harvard T.H. Chan School of Public Health<br>
        655 Huntington Ave, 2-410 | Boston, MA 02115<br>
        <a href="mailto:[email protected]">[email protected]</a><br>
        <a href="https://www.hsph.harvard.edu/qbrc">https://www.hsph.harvard.edu/qbrc</a>   
        </div>
    </body>
    </html>
    '''

    plaintext_template = '''
        %s
        
        -qBRC Team

        Quantitative Biomedical Research Center (qBRC)
        Dept. of Biostatistics | Harvard T.H. Chan School of Public Health
        655 Huntington Ave, 2-410 | Boston, MA 02115
        Email: [email protected]
        https://www.hsph.harvard.edu/qbrc 
    '''

    full_html = html_template % message_html
    full_plaintext = plaintext_template % plaintext_msg

    if recipient in settings.TEST_EMAIL_ADDRESSES:
        print('Sending mock email to %s' % recipient)
    else:
        j = json.load(open(settings.EMAIL_CREDENTIALS_FILE))
        credentials = Credentials(j['token'],
                                  refresh_token=j['refresh_token'],
                                  token_uri=j['token_uri'],
                                  client_id=j['client_id'],
                                  client_secret=j['client_secret'],
                                  scopes=j['scopes'])

        service = discovery.build('gmail', 'v1', credentials=credentials)

        sender = '*****@*****.**'
        message = MIMEMultipart('alternative')

        # create the plaintext portion
        part1 = MIMEText(full_plaintext, 'plain')

        # create the html:
        part2 = MIMEText(full_html, 'html')

        message.attach(part1)
        message.attach(part2)

        message['To'] = recipient
        message['From'] = formataddr((str(Header('QBRC', 'utf-8')), sender))
        message['subject'] = subject
        msg = {
            'raw':
            base64.urlsafe_b64encode(message.as_string().encode()).decode()
        }
        sent_message = service.users().messages().send(userId='me',
                                                       body=msg).execute()
def formatAddr(mail):
    name, addr = parseaddr(mail)
    return formataddr((Header(name, 'utf-8').encode(), addr))
Exemple #52
0
def format_addresses(addresses, names=[]):
    """
    Format destination (To) input.
    Input may be a string or sequence of strings;
    returns a well-formatted address string.

    :param addresses: [required] Mail addresses.
    :type addresses: sequence or string
    :param names: Names corresponding to mail addresses.
    :type addresses: sequence or string
    :returns: Well formatted address string.
    :rtype: String

    >>> from collective.easyform.api import format_addresses

    >>> format_addresses('*****@*****.**')
    '*****@*****.**'

    >>> format_addresses('*****@*****.**', 'sim')
    'sim <*****@*****.**>'

    >>> format_addresses('ähm@öhm.ühm', 'ähm')
    '\xc3\xa4hm <\xc3\xa4hm@\xc3\xb6hm.\xc3\xbchm>'

    >>> format_addresses('[email protected], [email protected]')
    '[email protected], [email protected]'

    >>> format_addresses('[email protected]\[email protected]')
    '[email protected], [email protected]'

    >>> format_addresses('[email protected], [email protected]', 'sim')
    'sim <*****@*****.**>, [email protected]'

    >>> format_addresses('[email protected], [email protected]', 'sim, hokus')
    'sim <*****@*****.**>, hokus <*****@*****.**>'

    >>> format_addresses('[email protected], [email protected]', 'sim\nhokus')
    'sim <*****@*****.**>, hokus <*****@*****.**>'

    >>> format_addresses(['*****@*****.**', '*****@*****.**'],
    ...                      ['sim', 'hokus'])
    'sim <*****@*****.**>, hokus <*****@*****.**>'

    >>> format_addresses(('*****@*****.**', '*****@*****.**'),
    ...                      ('sim', 'hokus'))
    'sim <*****@*****.**>, hokus <*****@*****.**>'

    >>> format_addresses([])
    ''

    >>> format_addresses('')
    ''

    """
    if type(addresses) in StringTypes:
        # replace common separators `;` and `,` with newlines so the
        # splitlines method works
        addresses = addresses.replace(',', '\n').replace(';', '\n')
        addresses = [s.strip() for s in addresses.splitlines()]
    assert (isinstance(addresses, list)
            or isinstance(addresses, tuple))  # ensure iterable  # noqa
    addresses = [
        safe_unicode(s).strip().encode('utf-8') for s in addresses if s
    ]

    if names and type(names) in StringTypes:
        # replace common separators `;` and `,` with newlines so the
        # splitlines method works
        names = names.replace(',', '\n').replace(';', '\n')
        names = [s for s in names.splitlines()]
    if not names:
        names = []
    assert (isinstance(names, list) or isinstance(names, tuple))
    names = [safe_unicode(s).strip().encode('utf-8') for s in names if s]

    address_pairs = []
    for cnt, address in enumerate(addresses):
        address_pairs.append(
            (names[cnt] if len(names) > cnt else False, address))
    ret = ', '.join([formataddr(pair) for pair in address_pairs])
    return ret
def main():

    module = AnsibleModule(
        argument_spec=dict(username=dict(default=None),
                           password=dict(default=None, no_log=True),
                           host=dict(default='localhost'),
                           port=dict(default='25'),
                           sender=dict(default='root', aliases=['from']),
                           to=dict(default='root', aliases=['recipients']),
                           cc=dict(default=None),
                           bcc=dict(default=None),
                           subject=dict(required=True, aliases=['msg']),
                           body=dict(default=None),
                           attach=dict(default=None),
                           headers=dict(default=None),
                           charset=dict(default='us-ascii'),
                           subtype=dict(default='plain')))

    username = module.params.get('username')
    password = module.params.get('password')
    host = module.params.get('host')
    port = module.params.get('port')
    sender = module.params.get('sender')
    recipients = module.params.get('to')
    copies = module.params.get('cc')
    blindcopies = module.params.get('bcc')
    subject = module.params.get('subject')
    body = module.params.get('body')
    attach_files = module.params.get('attach')
    headers = module.params.get('headers')
    charset = module.params.get('charset')
    subtype = module.params.get('subtype')
    sender_phrase, sender_addr = parseaddr(sender)

    if not body:
        body = subject

    try:
        try:
            smtp = smtplib.SMTP_SSL(host, port=int(port))
        except (smtplib.SMTPException, ssl.SSLError):
            smtp = smtplib.SMTP(host, port=int(port))
    except Exception:
        e = get_exception()
        module.fail_json(
            rc=1,
            msg='Failed to send mail to server %s on port %s: %s' %
            (host, port, e))

    smtp.ehlo()
    if username and password:
        if smtp.has_extn('STARTTLS'):
            smtp.starttls()
        try:
            smtp.login(username, password)
        except smtplib.SMTPAuthenticationError:
            module.fail_json(
                msg=
                "Authentication to %s:%s failed, please check your username and/or password"
                % (host, port))

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = formataddr((sender_phrase, sender_addr))
    msg.preamble = "Multipart message"

    if headers is not None:
        for hdr in [x.strip() for x in headers.split('|')]:
            try:
                h_key, h_val = hdr.split('=')
                msg.add_header(h_key, h_val)
            except:
                pass

    if 'X-Mailer' not in msg:
        msg.add_header('X-Mailer', "Ansible")

    to_list = []
    cc_list = []
    addr_list = []

    if recipients is not None:
        for addr in [x.strip() for x in recipients.split(',')]:
            to_list.append(formataddr(parseaddr(addr)))
            addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    if copies is not None:
        for addr in [x.strip() for x in copies.split(',')]:
            cc_list.append(formataddr(parseaddr(addr)))
            addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    if blindcopies is not None:
        for addr in [x.strip() for x in blindcopies.split(',')]:
            addr_list.append(parseaddr(addr)[1])

    if len(to_list) > 0:
        msg['To'] = ", ".join(to_list)
    if len(cc_list) > 0:
        msg['Cc'] = ", ".join(cc_list)

    part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset)
    msg.attach(part)

    if attach_files is not None:
        for file in attach_files.split():
            try:
                fp = open(file, 'rb')

                part = MIMEBase('application', 'octet-stream')
                part.set_payload(fp.read())
                fp.close()

                encoders.encode_base64(part)

                part.add_header('Content-disposition',
                                'attachment',
                                filename=os.path.basename(file))
                msg.attach(part)
            except Exception:
                e = get_exception()
                module.fail_json(
                    rc=1,
                    msg="Failed to send mail: can't attach file %s: %s" %
                    (file, e))

    composed = msg.as_string()

    try:
        smtp.sendmail(sender_addr, set(addr_list), composed)
    except Exception:
        e = get_exception()
        module.fail_json(rc=1,
                         msg='Failed to send mail to %s: %s' %
                         (", ".join(addr_list), e))

    smtp.quit()

    module.exit_json(changed=False)
Exemple #54
0
def do_send_missedmessage_events_reply_in_zulip(user_profile, missed_messages,
                                                message_count):
    # type: (UserProfile, List[Message], int) -> None
    """
    Send a reminder email to a user if she's missed some PMs by being offline.

    The email will have its reply to address set to a limited used email
    address that will send a zulip message to the correct recipient. This
    allows the user to respond to missed PMs, huddles, and @-mentions directly
    from the email.

    `user_profile` is the user to send the reminder to
    `missed_messages` is a list of Message objects to remind about they should
                      all have the same recipient and subject
    """
    from zerver.context_processors import common_context
    # Disabled missedmessage emails internally
    if not user_profile.enable_offline_email_notifications:
        return

    recipients = set(
        (msg.recipient_id, msg.subject) for msg in missed_messages)
    if len(recipients) != 1:
        raise ValueError(
            'All missed_messages must have the same recipient and subject %r' %
            recipients)

    unsubscribe_link = one_click_unsubscribe_link(user_profile,
                                                  "missed_messages")
    context = common_context(user_profile)
    context.update({
        'name':
        user_profile.full_name,
        'messages':
        build_message_list(user_profile, missed_messages),
        'message_count':
        message_count,
        'mention':
        missed_messages[0].recipient.type == Recipient.STREAM,
        'unsubscribe_link':
        unsubscribe_link,
    })

    # If this setting (email mirroring integration) is enabled, only then
    # can users reply to email to send message to Zulip. Thus, one must
    # ensure to display warning in the template.
    if settings.EMAIL_GATEWAY_PATTERN:
        context.update({
            'reply_warning': False,
            'reply_to_zulip': True,
        })
    else:
        context.update({
            'reply_warning': True,
            'reply_to_zulip': False,
        })

    from zerver.lib.email_mirror import create_missed_message_address
    reply_to_address = create_missed_message_address(user_profile,
                                                     missed_messages[0])
    if reply_to_address == FromAddress.NOREPLY:
        reply_to_name = None
    else:
        reply_to_name = "Zulip"

    senders = list(set(m.sender for m in missed_messages))
    if (missed_messages[0].recipient.type == Recipient.HUDDLE):
        display_recipient = get_display_recipient(missed_messages[0].recipient)
        # Make sure that this is a list of strings, not a string.
        assert not isinstance(display_recipient, Text)
        other_recipients = [
            r['full_name'] for r in display_recipient
            if r['id'] != user_profile.id
        ]
        context.update({'group_pm': True})
        if len(other_recipients) == 2:
            huddle_display_name = u"%s" % (" and ".join(other_recipients))
            context.update({'huddle_display_name': huddle_display_name})
        elif len(other_recipients) == 3:
            huddle_display_name = u"%s, %s, and %s" % (
                other_recipients[0], other_recipients[1], other_recipients[2])
            context.update({'huddle_display_name': huddle_display_name})
        else:
            huddle_display_name = u"%s, and %s others" % (', '.join(
                other_recipients[:2]), len(other_recipients) - 2)
            context.update({'huddle_display_name': huddle_display_name})
    elif (missed_messages[0].recipient.type == Recipient.PERSONAL):
        context.update({'private_message': True})
    else:
        # Keep only the senders who actually mentioned the user
        #
        # TODO: When we add wildcard mentions that send emails, add
        # them to the filter here.
        senders = list(
            set(m.sender for m in missed_messages
                if UserMessage.objects.filter(
                    message=m,
                    user_profile=user_profile,
                    flags=UserMessage.flags.mentioned).exists()))
        context.update({'at_mention': True})

    context.update({
        'sender_str':
        ", ".join(sender.full_name for sender in senders),
        'realm_str':
        user_profile.realm.name,
    })

    from_name = "Zulip missed messages"  # type: Text
    from_address = FromAddress.NOREPLY
    if len(senders) == 1 and settings.SEND_MISSED_MESSAGE_EMAILS_AS_USER:
        # If this setting is enabled, you can reply to the Zulip
        # missed message emails directly back to the original sender.
        # However, one must ensure the Zulip server is in the SPF
        # record for the domain, or there will be spam/deliverability
        # problems.
        sender = senders[0]
        from_name, from_address = (sender.full_name, sender.email)
        context.update({
            'reply_warning': False,
            'reply_to_zulip': False,
        })

    email_dict = {
        'template_prefix': 'zerver/emails/missed_message',
        'to_user_id': user_profile.id,
        'from_name': from_name,
        'from_address': from_address,
        'reply_to_email': formataddr((reply_to_name, reply_to_address)),
        'context': context
    }
    queue_json_publish("missedmessage_email_senders",
                       email_dict,
                       send_email_from_dict,
                       call_consume_in_tests=True)

    user_profile.last_reminder = timezone_now()
    user_profile.save(update_fields=['last_reminder'])
Exemple #55
0
    def perform_request(self):
        """
        Perform the reporting.
        """

        # Be sure to use bare root URL http://.../FeatureServer
        ghc_url = self._resource.url.split('?')[0]

        # Assemble request templates with root FS URL

        summary_url = ghc_url + '/api/v1.0/summary/'

        # 1. Get the summary (JSON) report from GHC endpoint
        result = Result(True, 'Get GHC Report')
        result.start()
        try:
            response = self.perform_get_request(summary_url)
            status = response.status_code
            overall_status = status / 100
            if overall_status in [4, 5]:
                raise Exception('HTTP Error status=%d reason=%s' %
                                (status, response.reason))

            summary_report = response.json()
        except Exception as err:
            msg = 'Cannot get summary from %s err=%s' % \
                  (summary_url, str(err))
            result.set(False, msg)
            result.stop()
            self.result.add_result(result)
            return

        # ASSERTION - summary report fetch ok

        # 2. Do email reporting with summary report
        result = Result(True, 'Send Email')
        result.start()

        try:
            config = App.get_config()

            # Create message body with report
            template_vars = {'summary': summary_report, 'config': config}

            msg_body = render_template2('status_report_email.txt',
                                        template_vars)

            resource = self._resource
            to_addrs = self._parameters.get('email', None)
            if to_addrs is None:
                raise Exception(
                    'No emails set for GHCEmailReporter in resource=%s' %
                    resource.identifier)

            to_addrs = to_addrs.replace(' ', '')
            if len(to_addrs) == 0:
                raise Exception(
                    'No emails set for GHCEmailReporter in resource=%s' %
                    resource.identifier)

            to_addrs = to_addrs.split(',')
            msg = MIMEText(msg_body, 'plain', 'utf-8')
            msg['From'] = formataddr(
                (config['GHC_SITE_TITLE'], config['GHC_ADMIN_EMAIL']))
            msg['To'] = ', '.join(to_addrs)
            msg['Subject'] = '[%s] %s' % (config['GHC_SITE_TITLE'],
                                          gettext('Status summary'))

            from_addr = '%s <%s>' % (config['GHC_SITE_TITLE'],
                                     config['GHC_ADMIN_EMAIL'])

            msg_text = msg.as_string()
            send_email(config['GHC_SMTP'], from_addr, to_addrs, msg_text)
        except Exception as err:
            msg = 'Cannot send email. Contact admin: '
            LOGGER.warning(msg + ' err=' + str(err))
            result.set(False, 'Cannot send email: %s' % str(err))

        result.stop()

        # Add to overall Probe result
        self.result.add_result(result)
Exemple #56
0
def do_send_missedmessage_events_reply_in_zulip(user_profile: UserProfile,
                                                missed_messages: List[Dict[str, Any]],
                                                message_count: int) -> None:
    """
    Send a reminder email to a user if she's missed some PMs by being offline.

    The email will have its reply to address set to a limited used email
    address that will send a zulip message to the correct recipient. This
    allows the user to respond to missed PMs, huddles, and @-mentions directly
    from the email.

    `user_profile` is the user to send the reminder to
    `missed_messages` is a list of dictionaries to Message objects and other data
                      for a group of messages that share a recipient (and topic)
    """
    from zerver.context_processors import common_context
    # Disabled missedmessage emails internally
    if not user_profile.enable_offline_email_notifications:
        return

    recipients = {(msg['message'].recipient_id, msg['message'].topic_name()) for msg in missed_messages}
    if len(recipients) != 1:
        raise ValueError(
            'All missed_messages must have the same recipient and topic %r' %
            (recipients,)
        )

    # This link is no longer a part of the email, but keeping the code in case
    # we find a clean way to add it back in the future
    unsubscribe_link = one_click_unsubscribe_link(user_profile, "missed_messages")
    context = common_context(user_profile)
    context.update({
        'name': user_profile.full_name,
        'message_count': message_count,
        'unsubscribe_link': unsubscribe_link,
        'realm_name_in_notifications': user_profile.realm_name_in_notifications,
    })

    triggers = list(message['trigger'] for message in missed_messages)
    unique_triggers = set(triggers)
    context.update({
        'mention': 'mentioned' in unique_triggers or 'wildcard_mentioned' in unique_triggers,
        'stream_email_notify': 'stream_email_notify' in unique_triggers,
        'mention_count': triggers.count('mentioned') + triggers.count("wildcard_mentioned"),
    })

    # If this setting (email mirroring integration) is enabled, only then
    # can users reply to email to send message to Zulip. Thus, one must
    # ensure to display warning in the template.
    if settings.EMAIL_GATEWAY_PATTERN:
        context.update({
            'reply_to_zulip': True,
        })
    else:
        context.update({
            'reply_to_zulip': False,
        })

    from zerver.lib.email_mirror import create_missed_message_address
    reply_to_address = create_missed_message_address(user_profile, missed_messages[0]['message'])
    if reply_to_address == FromAddress.NOREPLY:
        reply_to_name = None
    else:
        reply_to_name = "Zulip"

    narrow_url = get_narrow_url(user_profile, missed_messages[0]['message'])
    context.update({
        'narrow_url': narrow_url,
    })

    senders = list({m['message'].sender for m in missed_messages})
    if (missed_messages[0]['message'].recipient.type == Recipient.HUDDLE):
        display_recipient = get_display_recipient(missed_messages[0]['message'].recipient)
        # Make sure that this is a list of strings, not a string.
        assert not isinstance(display_recipient, str)
        other_recipients = [r['full_name'] for r in display_recipient
                            if r['id'] != user_profile.id]
        context.update({'group_pm': True})
        if len(other_recipients) == 2:
            huddle_display_name = " and ".join(other_recipients)
            context.update({'huddle_display_name': huddle_display_name})
        elif len(other_recipients) == 3:
            huddle_display_name = "%s, %s, and %s" % (
                other_recipients[0], other_recipients[1], other_recipients[2])
            context.update({'huddle_display_name': huddle_display_name})
        else:
            huddle_display_name = "%s, and %s others" % (
                ', '.join(other_recipients[:2]), len(other_recipients) - 2)
            context.update({'huddle_display_name': huddle_display_name})
    elif (missed_messages[0]['message'].recipient.type == Recipient.PERSONAL):
        context.update({'private_message': True})
    elif (context['mention'] or context['stream_email_notify']):
        # Keep only the senders who actually mentioned the user
        if context['mention']:
            senders = list({m['message'].sender for m in missed_messages
                            if m['trigger'] == 'mentioned' or
                            m['trigger'] == 'wildcard_mentioned'})
        message = missed_messages[0]['message']
        stream = Stream.objects.only('id', 'name').get(id=message.recipient.type_id)
        stream_header = "%s > %s" % (stream.name, message.topic_name())
        context.update({
            'stream_header': stream_header,
        })
    else:
        raise AssertionError("Invalid messages!")

    # If message content is disabled, then flush all information we pass to email.
    if not message_content_allowed_in_missedmessage_emails(user_profile):
        realm = user_profile.realm
        context.update({
            'reply_to_zulip': False,
            'messages': [],
            'sender_str': "",
            'realm_str': realm.name,
            'huddle_display_name': "",
            'show_message_content': False,
            'message_content_disabled_by_user': not user_profile.message_content_in_email_notifications,
            'message_content_disabled_by_realm': not realm.message_content_allowed_in_email_notifications,
        })
    else:
        context.update({
            'messages': build_message_list(user_profile, list(m['message'] for m in missed_messages)),
            'sender_str': ", ".join(sender.full_name for sender in senders),
            'realm_str': user_profile.realm.name,
            'show_message_content': True,
        })

    with override_language(user_profile.default_language):
        from_name = _("Zulip missed messages")  # type: str
    from_address = FromAddress.NOREPLY
    if len(senders) == 1 and settings.SEND_MISSED_MESSAGE_EMAILS_AS_USER:
        # If this setting is enabled, you can reply to the Zulip
        # missed message emails directly back to the original sender.
        # However, one must ensure the Zulip server is in the SPF
        # record for the domain, or there will be spam/deliverability
        # problems.
        #
        # Also, this setting is not really compatible with
        # EMAIL_ADDRESS_VISIBILITY_ADMINS.
        sender = senders[0]
        from_name, from_address = (sender.full_name, sender.email)
        context.update({
            'reply_to_zulip': False,
        })

    email_dict = {
        'template_prefix': 'zerver/emails/missed_message',
        'to_user_ids': [user_profile.id],
        'from_name': from_name,
        'from_address': from_address,
        'reply_to_email': formataddr((reply_to_name, reply_to_address)),
        'context': context}
    queue_json_publish("email_senders", email_dict)

    user_profile.last_reminder = timezone_now()
    user_profile.save(update_fields=['last_reminder'])
Exemple #57
0
        nameDIA, priceDIA, changeDIA, changesPercentageDIA, nameSPY, priceSPY,
        changeSPY, changesPercentageSPY)

today_formatted = today.strftime("%m/%d/%y")

#Enter email information
fromaddr = "*****@*****.**"
password = "******"
toaddr = ['*****@*****.**', '*****@*****.**']

# fakeCcList = ['*****@*****.**']
# bccList = ['*****@*****.**']
displayName = 'Stock Master'

msg = MIMEMultipart('alternative')
msg['From'] = formataddr((str(Header(displayName, 'utf-8')), fromaddr))

#Edit subject, message, and reply-to information here
msg['Subject'] = today_formatted + " Daily Stock Update"
stockInfo = "The stock market has just closed\n\n"
stockInfo = stockInfo + data
# msg.add_header('reply-to', "*****@*****.**")

## News Module

import requests
r = requests.get(
    'https://finnhub.io/api/v1/news?category=general&token=bsn0ifnrh5ret9gkabfg'
)
news = "\n\n\nNews\n" + json.dumps(r.json(), indent=4)
Exemple #58
0
 def _format_addr(self, s, encode_format='utf-8'):
     name, addr = parseaddr(s)
     return formataddr((Header(name, encode_format).encode(), addr))
Exemple #59
0
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))
Exemple #60
0
 def encode_addr(addr):
     name, email = addr
     if not try_coerce_ascii(name):
         name = str(Header(name, 'utf-8'))
     return formataddr((name, email))