Пример #1
0
 def _sendmail(self, smtphost, from_addr, to_addrs, msg, port=25):
     """ This is based on twisted.mail.smtp.sendmail except that it
     instantiates a quiet (noisy=False) SMTPSenderFactory """
     msg = StringIO(msg)
     d = defer.Deferred()
     factory = SMTPSenderFactory(from_addr, to_addrs, msg, d)
     factory.noisy = False
     reactor.connectTCP(smtphost, port, factory)
     return d
Пример #2
0
    def send_validation_fail_email(self, name, emails, error):
        """Notify the user via email about the tryjob error."""
        html_content = []
        html_content.append('<html><body>')
        body = """
Your tryjob with name '%(name)s' failed the validation step.  This is most
likely because <br>you are running an older version of cbuildbot.  Please run
<br><code>repo sync chromiumos/chromite</code> and try again.  If you still
see<br>this message please contact [email protected].<br>
"""
        html_content.append(body % {'name': name})
        html_content.append("Extra error information:")
        html_content.append(error.replace('\n', '<br>\n'))
        html_content.append(self.email_footer)
        m = Message()
        m.set_payload('<br><br>'.join(html_content), 'utf8')
        m.set_type("text/html")
        m['Date'] = formatdate(localtime=True)
        m['Subject'] = 'Tryjob failed validation'
        m['From'] = self.from_addr
        m['Reply-To'] = self.reply_to
        result = defer.Deferred()
        sender_factory = SMTPSenderFactory(self.from_addr, emails,
                                           StringIO(m.as_string()), result)
        reactor.connectTCP(self.smtp_host, 25, sender_factory)
Пример #3
0
    def sendmail(self, mail):
        recipients = flatten([mail.to, mail.cc, mail.bcc])

        resultDeferred = Deferred()
        senderFactory = SMTPSenderFactory(fromEmail=self.account_email_address,
                                          toEmail=recipients,
                                          file=StringIO(mail.to_smtp_format()),
                                          deferred=resultDeferred)

        return reactor.connectTCP('localhost', 4650, senderFactory)
Пример #4
0
def sendMessage(config):
    # Make a message
    msg = Message.Message()
    msgid = Utils.make_msgid()
    # remember the msgid so we can find it later
    config.msgid = msgid
    msg['To'] = config.toAddress
    msg['From'] = config.fromAddress
    msg['Message-ID'] = msgid
    msg['X-Zenoss-Time-Sent'] = str(config.sent)
    msg['Subject'] = 'Zenoss Round-Trip Mail Message'
    msg.set_payload(config.messageBody)
    log.debug("Message id %s's length is %s bytes" %
              (msgid, len(msg.as_string())))
    msgIO = StringIO(msg.as_string())
    result = defer.Deferred()

    # figure out how we should connect
    connect = reactor.connectTCP
    port = 25
    kwargs = {}
    args = ()
    if ssl and config.smtpAuth == 'SSL':
        port = 465
        connect = reactor.connectSSL
        kwargs.update(dict(requireTransportSecurity=False))
        args = (ssl.ClientContextFactory(), )
    elif ssl and config.smtpAuth == 'TLS':
        pass
    else:
        kwargs.update(dict(requireTransportSecurity=False))

    if config.smtpUsername:
        log.debug("ESMTP login as %s/%s" %
                  (config.smtpUsername, "*" * len(config.smtpPassword)))
        factory = ESMTPSenderFactory(config.smtpUsername, config.smtpPassword,
                                     config.fromAddress, (config.toAddress, ),
                                     msgIO, result, **kwargs)
    else:
        factory = SMTPSenderFactory(config.fromAddress, (config.toAddress, ),
                                    msgIO, result)

    def clientConnectionFailed(self, why):
        result.errback(why)

    factory.clientConnectionFailed = clientConnectionFailed

    # initiate the message send
    log.debug("Sending message to %s:%s with args: %s" %
              (config.smtpHost, config.smtpPort or port, args))
    connect(config.smtpHost, config.smtpPort or port, factory, *args)
    return result
Пример #5
0
    def sendmail(self, mail):
        if self.ensure_smtp_is_running_cb():
            recipients = flatten([mail.to, mail.cc, mail.bcc])
            result_deferred = Deferred()
            sender_factory = SMTPSenderFactory(
                fromEmail=self.account_email_address,
                toEmail=set([parseaddr(recipient)[1] for recipient in recipients]),
                file=StringIO(mail.to_smtp_format()),
                deferred=result_deferred)

            reactor.connectTCP('localhost', 4650, sender_factory)

            return result_deferred
        return fail(SMTPDownException())
Пример #6
0
def sendMessageFile(
    fromAddress,
    toAddress,
    messageFile,
    smtpHost=None,
    smtpPort=None,
    smtpUsername=None,
    smtpPassword=None,
):
    """
    @param smtpUsername: The username with which to authenticate.
    @param smtpPassword: The password with which to authenticate.
    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param messageFile: A file-like object containing the headers and body of
    the message to send.
    @param smtpHost: The MX host to which to connect.
    @param smtpPort: The port number to which to connect.

    @return: A Deferred which will be called back when the message has been
    sent or which will errback if it cannot be sent.
    """

    resultDeferred = defer.Deferred()

    smtpPort = smtpPort or settings.EMAIL_PORT
    smtpHost = smtpHost or settings.EMAIL_HOST
    smtpUsername = smtpUsername or settings.EMAIL_USER
    smtpPassword = smtpPassword or settings.EMAIL_PASSWORD

    if smtpUsername or smtpPassword:
        senderFactory = ESMTPSenderFactory(
            smtpUsername,
            smtpPassword,
            fromAddress,
            toAddress,
            messageFile,
            resultDeferred,
        )
    else:
        senderFactory = SMTPSenderFactory(
            fromAddress,
            toAddress,
            messageFile,
            resultDeferred,
        )
    reactor.connectTCP(smtpHost, smtpPort, senderFactory)
    return resultDeferred
Пример #7
0
    def sendEmail(self, mEntity, subject, content):
        #self.dst_phone = self.getProp(self.__class__.PROP_DST_PHONE)

        timestamp = mEntity.getTimestamp()
        srcShort = mEntity.getFrom(full=False)

        formattedDate = datetime.datetime.fromtimestamp(timestamp) \
                                         .strftime('%d/%m/%Y %H:%M')
        content2 = "%s\n\nAt %s by %s (%s) isBroadCast=%s" \
                % (content, formattedDate, srcShort, mEntity.getParticipant(),
                    mEntity.isBroadcast())

        smtp_user = self.getProp(self.__class__.PROP_USER)
        dst_mail = self.getProp(self.__class__.PROP_DST_MAIL)
        reply_mail = self.getProp(self.__class__.PROP_REPLY_MAIL, None)
        msg = MIMEText(content2, 'plain', 'utf-8')
        msg['To'] = "WhatsApp <%s>" % (dst_mail)
        msg['From'] = "%s <%s>" % (srcShort, mEntity.getParticipant())
        msg['Reply-To'] = "%s <%s>" % (mEntity.getParticipant(), reply_mail)
        msg['Subject'] = subject
        msg['Date'] = formatdate(timestamp)
        msg_file = StringIO(msg.as_string())

        def success(r):
            print("Mail sent")

        def error(err):
            err.printTraceback()
            print("Smtp error ", err)

        dfr = defer.Deferred()
        dfr.addCallback(success)
        dfr.addErrback(error)
        if smtp_user:
            smtp_pass = self.getProp(self.__class__.PROP_PASS)
            factory = ESMTPSenderFactory(smtp_user, smtp_pass, reply_mail,
                                         dst_mail, msg_file, dfr)
        else:
            factory = SMTPSenderFactory(reply_mail, dst_mail, msg_file, dfr)

        endpoint = self.getProp(self.__class__.PROP_ENDPOINT)
        smtp_endpoint = endpoints.clientFromString(reactor, endpoint)
        smtp_endpoint.connect(factory)

        #s.sendmail(dst, [dst], msg.as_string())
        print("=> Mail: %s -> %s" % (reply_mail, dst_mail))