Example #1
0
def postino_raw(text=None,
                html=None,
                subject=None,
                to=[],
                cc=[],
                bcc=[],
                cfg=None):

    if cfg is None:
        raise PostinoError('No configuration specified')

    if subject is None:
        raise PostinoError('No subject specified')

    if text is None and html is None:
        raise PostinoError('No body specified')

    if not compat.isunicode(subject):
        raise PostinoError('Subject must be a unicode string')

    if not (compat.isunicode(text) or compat.isunicode(html)):
        raise PostinoError('Body must be a unicode string')

    if not to:
        raise PostinoError('No recipients')

    for addr in to + cc + bcc:
        if not isinstance(addr, Address):
            raise PostinoError('Address of invalid type')

    def encode_text(text, encoding='utf-8'):
        if text is None:
            return None
        return (text.encode(encoding), encoding)

    convert_address = lambda addr: addr.to_pyzmail()
    convert_addresses = lambda a: [convert_address(e) for e in a]

    # all looks OK, create and send the email
    payload, mail_from, rcpt_to, msg_id = compose_mail(
        convert_address(cfg.sender),
        convert_addresses(to),
        cc=convert_addresses(cc),
        bcc=convert_addresses(bcc),
        subject=subject.replace('\n', ' ').strip(),
        default_charset='utf-8',
        text=encode_text(text),
        html=encode_text(html))

    ret = send_mail(payload,
                    mail_from,
                    rcpt_to,
                    cfg.server,
                    smtp_port=cfg.port,
                    smtp_mode=cfg.mode,
                    smtp_login=cfg.login,
                    smtp_password=cfg.password)

    if ret:
        raise PostinoError('Failed sending: %s' % ret)
Example #2
0
def send_mail(sender, recipients, subject, text_content, headers=[]):
    """
    Sends email using pyzmail
    """
    prefered_encoding = 'iso-8859-1'
    text_encoding = 'iso-8859-1'

    smtp_host = EMAIL_HOST
    smtp_port = EMAIL_PORT
    smtp_mode = 'tls' if EMAIL_USE_TLS else 'normal'
    smtp_login = EMAIL_HOST_USER if EMAIL_HOST_USER != '' else None
    smtp_password = EMAIL_HOST_PASSWORD if EMAIL_HOST_USER != '' else None

    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
        ("Reuse Mobile", sender),
        recipients,
        subject,
        prefered_encoding,
        (text_content, text_encoding),
        html=None, headers=headers)

    ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode,
                            smtp_login=smtp_login, smtp_password=smtp_password)


    if isinstance(ret, dict):
        if ret:
            return 'failed recipients:' + ','.join(ret.keys())
        else:
            return 'success'
    else:

        return 'error: ' + ret + "\n\n "+ ' from: ' + mail_from + " host: " +smtp_host+" port: "+ str(smtp_port) + " mode: " + smtp_mode + " login: "******" password: " + str(smtp_password)
Example #3
0
    def send_email(self):
        """

        :return: tuple, True/False, details
        """

        payload, mail_from, rcpt_to, msg_id = self.compose_email()

        # Send the email:
        ret = pyzmail.send_mail(payload,
                                mail_from,
                                rcpt_to,
                                smtp_host=self.smtp_host,
                                smtp_port=self.smtp_port,
                                smtp_mode=self.smtp_mode,
                                smtp_login=self.smtp_login,
                                smtp_password=self.smtp_password)

        if isinstance(ret, dict):
            if ret:
                return False, 'failed recipients:', ', '.join(ret.keys())
            else:
                return True, 'success'
        else:
            return False, 'error:', ret
Example #4
0
def process(filename):

    path = get_path(filename)
    blob = read_blob(path)

    mid = blob["id"]

    print "Sending message", mid

    payload, mail_from, rcpt_to, msg_id = assemble_email(blob)

    print "Writing payload to", path
    write_to_file(path, payload)

    error = pyzmail.send_mail(payload,
                              mail_from,
                              rcpt_to,
                              'localhost',
                              smtp_port=25)

    if error:
        if isinstance(error, str):
            print "Sending failed: '%s'" % error
        else:
            print "Can't send to some recepients: %s" % error
        sys.exit(1)

    print "Success"
Example #5
0
def send_email(title, content, send_filepaths):

    email_sender = conf.SMTP_LOGIN
    email_receivers = conf.EMAIL_RECEIVERS.split(';')
    smtp_host = conf.SMTP_HOST
    smtp_port = conf.SMTP_PORT
    smtp_mode = conf.SMTP_MODE
    smtp_login = conf.SMTP_LOGIN
    smtp_password = conf.SMTP_PASSWORD

    import pyzmail
    attach_files = []
    for send_filepath in send_filepaths:
        filename = os.path.basename(send_filepath)
        attach_file = (open(send_filepath).read(), 'application',
                       'octet-stream', filename, '')
        attach_files.append(attach_file)
    payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(email_sender, \
                    email_receivers, title, \
                    'utf-8', None, html=(content, 'utf-8'),
                    attachments=attach_files)
    ret=pyzmail.send_mail(payload, email_sender, rcpt_to, smtp_host, \
            smtp_port=smtp_port, smtp_mode=smtp_mode, \
            smtp_login=smtp_login, smtp_password=smtp_password)
    print(ret)
def send_mail_from_note(note, smtp_host, smtp_port, smtp_login, smtp_password, smtp_mode, sender, to, debug=False, verbose=False):

    counter = 1
    resources = {}
    images = []
    if note.resources:
        for r in note.resources:
            k = r.data.bodyHash.encode('hex')
            fn = '%.2i.%s' % (counter, mimetypes.guess_extension(r.mime)[1:])
            resources[k] = 'cid:' + fn
            a, b = r.mime.split('/')
            images.append((r.data.body, a, b, fn, None))
            counter += 1

    text_content = PlainTextOfENML(note.content)
    html_content = HTMLOfENML(note.content, resources)
    title = note.title
    #title = 'La note de %sh' % datetime.now().strftime('%H')

    try:
        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
            sender=sender,
            recipients=to,
            subject=title,
            default_charset='utf-8',
            text=(text_content, 'utf-8'),
            html=(html_content, 'utf-8'),
            attachments=None,
            embeddeds=images,)
            #headers=(('Reply-To', '*****@*****.**' % str(note.guid)), ))

        ret = pyzmail.send_mail(payload=payload,
                                mail_from=mail_from,
                                rcpt_to=rcpt_to,
                                smtp_host=smtp_host,
                                smtp_port=smtp_port,
                                smtp_mode=smtp_mode,
                                smtp_login=smtp_login,
                                smtp_password=smtp_password)
            
        if isinstance(ret, dict):
            if ret:
                if verbose:
                    print >> sys.stderr, 'failed recipients:', ', '.join(ret.keys())
            else:
                if verbose:
                    print >> sys.stderr, 'success'
        else:
            if verbose:
                print >> sys.stderr, 'error:', ret

    except Exception, e:
        raise
        return 1
Example #7
0
def alert(game):
    text = "There's a Giants game tomorrow at AT&T park. The game should end around %s. Plan accordingly. Game end time : %s" % (
        game.strftime("%I:%M %p"), game.strftime("%c"))
    logging.debug("Emailing : %s" % text)
    compose_args = {
        'sender': ("Is there a Giants game tomorrow", SENDER),
        'recipients': [RECIPIENT],
        'subject': "There's a Giants game tomorrow",
        'default_charset': 'iso-8859-1',
        'text': (text, 'us-ascii')
    }
    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(**compose_args)
    return pyzmail.send_mail(payload, mail_from, rcpt_to, 'localhost')
Example #8
0
    def send_email_pyzmail(self, maildict):
        """Send a mail message.
        pyzmail is supposed to be good but my experience with it has been terrible.  It fails mysteriously and takes minutes to time out.
        and the compose_mail function seems to return broken value from mail_from return argument.
        """

        # mail settings
        mailsettings = self.get_setting_value(mconst.DEF_SETTINGSEC_mail)

        # parameters
        efrom = mailsettings['mail_from']
        eto = maildict['to']
        esubject = maildict['subject']
        ebody = maildict['body']
        preferred_encoding = 'iso-8859-1'
        text_encoding = preferred_encoding

        # ensure eto is a list
        if (isinstance(eto, basestring)):
            eto = [eto]

        # compose email and create payload
        (payload, mail_from, rcpt_to, msg_id) = pyzmail.compose_mail(efrom, eto, esubject, preferred_encoding, (ebody,text_encoding))
        # ATTN: return value of mail_from is bad, and was causing failure to send email for hours before identified

        #print payload
        #msg = pyzmail.PyzMessage.factory(payload)
        #print msg.get_subject()

        #print "MAIL SETTINGS: "+str(mailsettings)
        #print "MAIL FROM: "+mail_from
        #print "MAIL TO: "+str(rcpt_to)

        # smtp info for sending
        smtp_host = mailsettings['smtp_host']
        smtp_port = mailsettings['smtp_port']
        smtp_mode = mailsettings['smtp_mode']
        smtp_login = mailsettings['smtp_login']
        smtp_password = mailsettings['smtp_password']

        # actually send the mail
        ret=pyzmail.send_mail(payload, efrom, eto, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password)

        # check return value
        if isinstance(ret, dict):
            if ret:
                return EFailure('failed recipients: ' + ', '.join(ret.keys()))
            else:
                return None

        return EFailure('error:'+ ret)
Example #9
0
def sendEmail(overview, body, log_file_attachments):

	#encoded inline image
	logo=base64.b64decode(	"""R0lGODlhM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E040jjbRBOtdQkWBM6g9lkMIz3VATgB2kdpDAJAEg00sAhtxOwQ3dmJvJFlED/5Djww9RQMdqRN9JAKg44NDzATjDSjXV7ECBwmuEMkwA3PAwf+mnkVDvLalQAocU8IkGaQMHV2FfJYqQiwBYQTETQMMfAoGNAFzhdy4J3jKYIwYGWIAG2YNEH4QRAD8AxgCWaJAqQqCBDUSAF8zRhQjGFhPceKAMgoJDCy5wgRnUQQ0REAARW+AghaZYoAmCmkMZSKCTkdwhEpU4xA32xz+HOEBNcNKAAhqwgTM1AGteTJPWINKABCggAVKSW9dI8rU1aqSNbrQIHONYKjp+ZI52rGIe67jHjIxkIYAMpCAxEhAAOw==
	""")
	
	#Get Current Date & Time
	datetime_string = datetime.datetime.now().strftime('%A, %B %d, %Y | %H:%M%p %Z')
	
	#Create Email Template
	text_content=u'Daily Nodealyzer Report Content'
	with open (script_dir + "/email_template_inlined.html", "r") as template:
		html_content=template.read().replace('\n', '')
	
	#Fill in Template Information
	html_content = html_content.replace('[ENCODED_LOGO]', '<img src="cid:logo"/>')
	html_content = html_content.replace('[DATE_TIME]', datetime_string)
	html_content = html_content.replace('[TITLE]', 'Daily Nodealyzer Report')
	html_content = html_content.replace('[SUBTITLE]', config.get('ServerInfo','friendly_server_name'))
	html_content = html_content.replace('[PANEL]', overview)
	html_content = html_content.replace('[BODY]', body)
	html_content = html_content.replace('[FOOTER]', 'Generated by <a href="https://www.github.com/sciguy14/Nodealyzer" title="Nodealyzer on GitHub">Nodealyzer</a>')

        #Generate Log File attachment list
        attachment_list = []
        for filename in log_file_attachments:
                with open (filename, "r") as attachment_file:
                        attachment_text=attachment_file.read()
                attachment_list.append([attachment_text, 'text', 'plain', filename, 'us-ascii'])
	
	payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
        (config.get('ServerInfo','friendly_server_name'), config.get('ServerInfo','server_email')), \
        [(config.get('OwnerInfo','owner_name'), config.get('OwnerInfo','owner_email')),], \
        u'Daily Nodealyzer Report', \
        'iso-8859-1', \
        (text_content, 'iso-8859-1'), \
        (html_content, 'iso-8859-1'), \
        embeddeds=[(logo, 'image', 'gif', 'logo', None)], \
        attachments=attachment_list )

	ret=pyzmail.send_mail(payload, mail_from, rcpt_to, config.get('ServerInfo','smtp_host'), \
        smtp_port=config.get('ServerInfo','smtp_port'), smtp_mode=config.get('ServerInfo','smtp_mode'), \
        smtp_login=config.get('ServerInfo','smtp_login'), smtp_password=config.get('ServerInfo','smtp_password'))

	if isinstance(ret, dict):
		if ret:
			return 'Failed recipients:', ', '.join(ret.keys())
		else:
			return 'Success!'
	else:
		return 'Error:', ret
Example #10
0
 def send(self, to=None):
     if to is not None:
         orig_to = self.to
         self.to = to
         
     payload = self.generate()   # normalize()'ed
     ret = pyzmail.send_mail(
         payload, self.from_addr(), self.to_addr(),
         self.smtp[0], self.smtp[1], self.mode, self.user_name, self.password
     )
     
     if to is not None:
         self.to = orig_to
     return ret
Example #11
0
def send_email(title, content, send_filepath):
    import pyzmail
    filename = os.path.basename(send_filepath)
    attach_file = (open(send_filepath).read(), 'application', 'octet-stream',
                   filename, '')
    payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(email_sender, \
                    email_receivers, \
                    title, \
                    'utf-8', None, html=(content, 'utf-8'),
                    attachments=[attach_file])
    ret=pyzmail.send_mail(payload, email_sender, rcpt_to, smtp_host, \
            smtp_port=smtp_port, smtp_mode=smtp_mode, \
            smtp_login=smtp_login, smtp_password=smtp_password)
    print(ret)
def alert(game):
    text = (
        "There's a Giants game tomorrow at AT&T park. The game should end around %s. Plan accordingly. Game end time : %s"
        % (game.strftime("%I:%M %p"), game.strftime("%c"))
    )
    logging.debug("Emailing : %s" % text)
    compose_args = {
        "sender": ("Is there a Giants game tomorrow", SENDER),
        "recipients": [RECIPIENT],
        "subject": "There's a Giants game tomorrow",
        "default_charset": "iso-8859-1",
        "text": (text, "us-ascii"),
    }
    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(**compose_args)
    return pyzmail.send_mail(payload, mail_from, rcpt_to, "localhost")
Example #13
0
    def send_email_pyzmail(self, maildict):
        """Send a mail message.
        pyzmail is supposed to be good but my experience with it has been terrible.  It fails mysteriously and takes minutes to time out.
        and the compose_mail function seems to return broken value from mail_from return argument.
        """

        # mail settings
        mailsettings = self.get_setting_value(mconst.DEF_SETTINGSEC_mail)

        # parameters
        efrom = mailsettings['mail_from']
        eto = maildict['to']
        esubject = maildict['subject']
        ebody = maildict['body']
        preferred_encoding = 'iso-8859-1'
        text_encoding = preferred_encoding

        # compose email and create payload
        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(efrom, eto, esubject, preferred_encoding, (ebody,text_encoding))
        # ATTN: return value of mail_from is bad, and was causing failure to send email for hours before identified

        #print payload
        #msg = pyzmail.PyzMessage.factory(payload)
        #print msg.get_subject()

        #print "MAIL SETTINGS: "+str(mailsettings)
        #print "MAIL FROM: "+mail_from
        #print "MAIL TO: "+str(rcpt_to)

        # smtp info for sending
        smtp_host = mailsettings['smtp_host']
        smtp_port = mailsettings['smtp_port']
        smtp_mode = mailsettings['smtp_mode']
        smtp_login = mailsettings['smtp_login']
        smtp_password = mailsettings['smtp_password']

        # actually send the mail
        ret=pyzmail.send_mail(payload, efrom, eto, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password)

        # check return value
        if isinstance(ret, dict):
            if ret:
                return EFailure('failed recipients: ' + ', '.join(ret.keys()))
            else:
                return None

        return EFailure('error:'+ ret)
Example #14
0
    def send(self, mail_header, text='', html=None, file_list=None):

        # 构造邮件
        payload, mail_from, rcpt_to, msg_id = smtp.compose_mail(
            (self.__conf['profile']['name'],
             self.__conf['profile']['mailbox']),
            mail_header['recipients'],
            mail_header['subject'],
            'UTF-8', (text, 'UTF-8'),
            None if html is None else (html, 'UTF-8'),
            [] if file_list is None else Mail.__add_attachments(file_list),
            headers=mail_header['others']
            if mail_header.has_key('others') else [])

        # 发送邮件
        ret = smtp.send_mail(payload, mail_from, rcpt_to,
                             self.__conf['smtp']['server'],
                             self.__conf['smtp']['port'],
                             self.__conf['smtp']['mode'],
                             self.__conf['profile']['account'],
                             self.__conf['profile']['password'])

        # 发生错误
        if not isinstance(ret, dict):

            log.error('Send error: ' + ret)

            return False

        else:

            # 发送至某些收件人失败
            if ret:

                log.warning('Failed recipients: ')

                for recipient, (code, msg) in ret.iteritems():

                    log.warning('code: %d recipient: %s error: %s', code,
                                recipient, msg)

                return False

            # 发送成功
            log.info('Send to %s success.' % (rcpt_to))

            return True
Example #15
0
 def SendMessage(self, subject, msg):
     payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
         self.sender, self.recipients, unicode(subject),
         self.default_charset, (msg, self.encoding))
     ret = pyzmail.send_mail(payload, mail_from, rcpt_to, self.smtp_host,
                             self.smtp_port, self.smtp_mode,
                             self.smtp_login, self.smtp_password)
     if isinstance(ret, dict):
         if ret:
             str = 'failed recipients:' + ', '.join(ret.keys())
             raise SendMail.SendMailException(str)
         #    print 'failed recipients:', ', '.join(ret.keys())
         #else:
         #    print 'success'
     else:
         str = 'error:' + ret
         raise SendMail.SendMailException(str)
Example #16
0
def send_email:
        sender = (u'Security Force', '*****@*****.**')
        recipients = [(u'Boss', '*****@*****.**')]
        '''
        subject = u'Notification of a security breach'
        text_content = u'You have been alerted of an alleged security breach of your safe. Stay protected.'
        '''
        subject = u'Test message'
        text_content = u'This is a test message.'
        prefered_encoding = 'iso-8859-1'
        text_encoding = 'iso-8859-1'

        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(\
                sender, \
                recipients, \
                subject, \
                prefered_encoding, \
                (text_content, text_encoding), \
                html=None)#, \
                #attachments=[('attached content', 'text', 'plain', 'text.txt', \
                #		'us-ascii')])
        print payload

        print "------------------------------------------------------------"

        print 'Sender address: ', mail_from
        print 'Recipients: ', rcpt_to

        print "------------------------------------------------------------"

        smtp_host = "smtp.gmail.com"
        smtp_port = 587
        smtp_mode = 'tls'
        smtp_login = '******'
        smtp_password = '******'
        ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \
                smtp_port=smtp_port, smtp_mode=smtp_mode, \
                smtp_login=smtp_login, smtp_password=smtp_password)

        if isinstance(ret, dict):
                if ret:
                        print 'failed recipients: ', ', '.join(ret.keys())
                else:
                        print 'Boss has been alerted about the situation.'
        else:
                print 'error: ', ret
Example #17
0
def send_glenta(to, buy_for):
    message = MESSAGE % (to[0], buy_for)

    mail, mail_from, mail_to, msg_id = pyzmail.compose_mail(
        SMTP['from'],
        [to],
        SUBJECT,
        'utf-8',
        (message.encode('iso-8859-1'), 'iso-8859-1')
    )

    result = pyzmail.send_mail(
        mail, mail_from, mail_to,
        SMTP['host'], smtp_port=SMTP['port'], smtp_mode=SMTP['mode'],
        smtp_login=SMTP['login'], smtp_password=SMTP['password']
    )

    print result
Example #18
0
def sendmail(sender,recipients,subject,msg='',attach=[]):
    payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
        sender, \
        recipients, \
        subject, \
        'utf-8', \
        (msg, 'utf-8'), \
        html=None, \
        attachments=attach)

    #[('attached content', 'text', 'plain', 'text.txt', 'utf-8')]
    smtp_host = SMTP_HOST
    ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=smtp['port'], smtp_mode=smtp['mode'],smtp_login=smtp['username'],smtp_password=smtp['password'])

    if isinstance(ret, dict):
        if ret:
            print('failed recipients:', ', '.join(ret.keys()))
    else:
        print('error:', ret)
Example #19
0
def send_mail(sender, recipients, subject, text_content, headers=[]):
    """
    Sends email using pyzmail
    """
    prefered_encoding = 'iso-8859-1'
    text_encoding = 'iso-8859-1'
    smtp_host = EMAIL_HOST
    smtp_port = EMAIL_PORT
    smtp_mode = 'tls' if EMAIL_USE_TLS else 'normal'
    smtp_login = EMAIL_HOST_USER if EMAIL_HOST_USER != '' else None
    smtp_password = EMAIL_HOST_PASSWORD if EMAIL_HOST_USER != '' else None

    headers.append(REUSE_HEADER)

    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
        ("Reuse Mobile", sender),
        recipients,
        subject,
        prefered_encoding,
        None,
        html=(text_content.replace("\n", "<br />\n"), "us-ascii"),
        headers=headers)

    ret = pyzmail.send_mail(payload,
                            mail_from,
                            rcpt_to,
                            smtp_host,
                            smtp_port=smtp_port,
                            smtp_mode=smtp_mode,
                            smtp_login=smtp_login,
                            smtp_password=smtp_password)

    if isinstance(ret, dict):
        if ret:
            return 'failed recipients:' + ','.join(ret.keys())
        else:
            return 'success'
    else:

        return 'error: ' + ret + "\n\n " + ' from: ' + mail_from + " host: " + smtp_host + " port: " + str(
            smtp_port) + " mode: " + smtp_mode + " login: "******" password: " + str(smtp_password)
def send():
    sender = (u'Canary RPi', '*****@*****.**')
    recipients = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']
    subject = u'PDF from RPi'
    text_content = u'Attached PDF'
    preferred_encoding = 'iso-8859-1'
    text_encoding = 'iso-8859-1'

    os.chdir('reports')
    newest_report = max(glob.iglob('*.[Pp][Dd][Ff]'), key=os.path.getctime)

    fp = open(newest_report, 'rb')
    pdf = MIMEApplication(fp.read())
    fp.close()
    pdf.add_header('Content-Disposition', 'attachment', filename=newest_report)
    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \
        sender, \
        recipients, \
        subject, \
        preferred_encoding, \
        (text_content, text_encoding), \
        html=None, \
        attachments=[pdf])

    smtp_host = 'smtp.gmail.com'
    smtp_port = 587
    smtp_mode = 'tls'
    smtp_login = '******'
    smtp_password = '******'

    ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \
                            smtp_port=smtp_port, smtp_mode=smtp_mode, \
                            smtp_login=smtp_login, smtp_password=smtp_password)

    if isinstance(ret, dict):
        if ret:
            print 'failed recipients:', ', '.join(ret.keys())
        else:
            print 'PDF emailed'
    else:
        print 'error:', ret
def send_answer(mail, answer):
    """
    Sends a first response to the customer before he receives the result.
    :param mail: The mail he has sent
    :param answer: The answer-class
    :return:
    """

    recipient = [mail['sender']]

    prefered_encoding = 'iso-8859-1'
    text_encoding = 'iso-8859-1'
    html_encoding = 'iso-8859-1'

    payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \
        myMailAddress, \
        recipient, \
        answer.subject, \
        prefered_encoding, \
        (answer.text, text_encoding), \
        (answer.html.encode(html_encoding), html_encoding), \
        attachments=[])

    print()
    print('send_answer')
    #print(payload)

    ret = pyzmail.send_mail(payload, myMailAddress, recipient, myMailHostOut, \
                            smtp_port=myMailHostOutPort, smtp_mode='tls', \
                            smtp_login=myMailAddress, smtp_password=myMailPasswd)
    #ret = 'derzeit kein Mailversand'

    if isinstance(ret, dict):
        if ret:
            print('failed recipient:', ', '.join(ret.keys()))
        else:
            print('success')
    else:
        print('error:', ret)
Example #22
0
    def send_email(cls, email, subject, html, attachments: list=None, embeddeds: list=None):
        """ Выполняет отправку email
        :param email:
        :param subject:
        :param html:
        :param attachments:
        :param embeddeds:
        :return:
        """
        try:
            mail_attachments = []
            if attachments:
                for attachment in attachments:
                    mimetype, subtype = cls.guess_mimetype(attachment["name"])
                    mail_attachments.append((attachment["bytes"], mimetype, subtype, attachment["name"], None))

            mail_embeddeds = []
            if embeddeds:
                for embedd in embeddeds:
                    mimetype, subtype = cls.guess_mimetype(embedd["name"])
                    mail_embeddeds.append((embedd["bytes"], mimetype, subtype, embedd["name"], None))

            payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
                os.environ.get("FROM"), [email], subject, "Utf-8", None,
                html=(html, "Utf-8"),
                attachments=mail_attachments,
                embeddeds=mail_embeddeds
            )

            result = pyzmail.send_mail(
                payload, os.environ.get("FROM"), rcpt_to, os.environ.get("SMTP_HOST"), os.environ.get("SMTP_PORT"), 'ssl',
                smtp_login=os.environ.get("SMTP_LOGIN"), smtp_password=os.environ.get("SMTP_PASSWORD")
            )
            if isinstance(result, str):
                raise EmailError(result)
            return True if result == {} else False
        except Exception as err:
            raise EmailError(str(err))
Example #23
0
    def send_email(self):
        """

        :return: tuple, True/False, details
        """

        payload, mail_from, rcpt_to, msg_id = self.compose_email()

        # Send the email:
        ret = pyzmail.send_mail(payload, mail_from, rcpt_to,
                                smtp_host=self.smtp_host,
                                smtp_port=self.smtp_port,
                                smtp_mode=self.smtp_mode,
                                smtp_login=self.smtp_login,
                                smtp_password=self.smtp_password)

        if isinstance(ret, dict):
            if ret:
                return False, 'failed recipients:', ', '.join(ret.keys())
            else:
                return True, 'success'
        else:
            return False, 'error:', ret
Example #24
0
def send_email_pyzmail(email_password, content, from_address, to_address,
                       smtp_name, port):
    try:
        b64 = base64.b64decode(content['b64img'])
        text_content = unicode(content['Data'])
        html_content = u'<html><body>' + content['Data'] + \
                       '<img src="cid:doge" />.\n' \
                       '</body></html>'
        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
            (unicode(from_address), from_address),
            [(unicode(to_address), to_address)],
            u'Halo',
            'iso-8859-1', (text_content, 'iso-8859-1'),
            (html_content, 'iso-8859-1'),
            embeddeds=[
                (b64, 'image', 'bmp', 'doge', None),
            ])

        ret = pyzmail.send_mail(payload,
                                from_address,
                                to_address,
                                smtp_name,
                                smtp_port=port,
                                smtp_mode='tls',
                                smtp_login=from_address,
                                smtp_password=email_password)
        if isinstance(ret, dict):
            if ret:
                float("A")
            else:
                pass
        else:
            float("A")
    except Exception, e:
        logger.error("bitmhalo: smtp send: %s, %s" %
                     (str(e), traceback.format_exc()))
        return False
Example #25
0
 def SendMessage(self, subject, msg):
     payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
         self.sender, self.recipients, unicode(subject), self.default_charset, (msg, self.encoding)
     )
     ret = pyzmail.send_mail(
         payload,
         mail_from,
         rcpt_to,
         self.smtp_host,
         self.smtp_port,
         self.smtp_mode,
         self.smtp_login,
         self.smtp_password,
     )
     if isinstance(ret, dict):
         if ret:
             str = "failed recipients:" + ", ".join(ret.keys())
             raise SendMail.SendMailException(str)
         #    print 'failed recipients:', ', '.join(ret.keys())
         # else:
         #    print 'success'
     else:
         str = "error:" + ret
         raise SendMail.SendMailException(str)
Example #26
0
def do_pull(repo, c):
    if repo['type'] == 'git':
        call(['cd "' + repo['path'] + git_pull.format(repo['branch']) + ' && ' + repo['command']], shell=True)
    else:
        call(['cd "' + repo['path'] + hg_pull + ' && ' + repo['command']], shell=True)
    if conf['email_notify']:
        sender = (conf['email_settings']['sender_name'], conf['email_settings']['sender_email'])
        recipients = repo['recipients']
        subject=u'「喵」 triggered on '+c['name']+':'+repo['branch']
        text_content='\n'.join([u'Miaopull was triggered by the commit', u"「喵噗哦」被以下提交觸發:", 'Message: '+c['msg'], 'ID: '+c['id']])
        prefered_encoding='utf-8'
        text_encoding='utf-8'

        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(sender, recipients, subject, prefered_encoding, (text_content, text_encoding), html=None)

        ret=pyzmail.send_mail(payload, mail_from, rcpt_to, conf['email_settings']['host'], smtp_port=conf['email_settings']['port'], smtp_mode=conf['email_settings']['mode'], smtp_login=conf['email_settings']['login'], smtp_password=conf['email_settings']['password'])

        if isinstance(ret, dict):
            if ret:
                print '[email notify] failed recipients:', ', '.join(ret.keys())
            else:
                print '[email notify] success'
        else:
            print '[email notify] error:', ret
Example #27
0
def process(filename):

    path = get_path(filename)
    blob = read_blob(path)

    mid = blob["id"]
    
    print "Sending message", mid

    payload, mail_from, rcpt_to, msg_id = assemble_email(blob)

    print "Writing payload to", path
    write_to_file(path, payload)

    error = pyzmail.send_mail(payload, mail_from, rcpt_to, 'localhost', smtp_port=25)

    if error:
        if isinstance(error, str):
            print "Sending failed: '%s'" % error
        else:
            print "Can't send to some recepients: %s" % error
        sys.exit(1)

    print "Success"
Example #28
0
print 'Sender: ', mail_from
print 'Recepient: ', rcpt_to
smtp_host = 'smtp.gmail.com'
smtp_port = 587
smtp_mode = 'tls'
smtp_login = raw_input('username: '******'\n! Received keyboard interrupt, quitting the app.\n'
	exit()


if isinstance(ret, dict):
	if ret:
		print 'failed recipient:', ', '.join(ret.keys())
	else:
		print 'success!'
else:
	print 'error:', ret
Example #29
0
def send_mail(subject, content, recipients, mail_settings, is_html=False):
    sender = (u'No reply', mail_settings["from"])
       
    prefered_encoding='utf-8'
    text_encoding='utf-8'
    
    dat = content, text_encoding
    if is_html:
        html = dat
        text_content = None
    else:
        html = None
        text_content = dat
    
    payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
            sender, \
            recipients, \
            subject, \
            prefered_encoding, \
            text_content, \
            html=html, \
            attachments=[
                #('attached content', 'text', 'plain', 'text.txt', 'us-ascii')
            ])
    
    #print payload
    #print mail_from, rcpt_to, msg_id
    
    smtp_provider = mail_settings["smtp_provider"]
    if smtp_provider == "gmail":
        smtp_host = 'smtp.gmail.com'
        kwargs = {
            "smtp_port": 587,
            "smtp_mode": 'tls',
            "smtp_login": sender[1],
            "smtp_password": mail_settings["password"]
        }
    elif smtp_provider == "1gb":
        kwargs = {
            #"smtp_port": 25, # либо 465, если не работает 25, см. в личном кабинете
        }
        
        # :TRICKY: согласно тех.поддержке 1gb.ru, слова которой подтвердил Тим,
        # для автоматической рассылки использовать нужно только robots.1gb.ru, а
        # те сервера, что указаны в учетках, предназначены для использования человеком
        # (Thunderbird, Outlook и т.д.)
        
        if mail_settings.get("is_robots_smtp"):
            smtp_host = 'robots.1gb.ru'
        else:
            smtp_host = 'smtp-9.1gb.ru'
            
            kwargs = {
                #"smtp_port": 25, # либо 465, если не работает 25, см. в личном кабинете
                "smtp_login":    mail_settings["login"],
                "smtp_password": mail_settings["password"],
            }
    else:
        assert False
    
    ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, **kwargs)

    # что делать в случае проблем?
    if isinstance(ret, dict):
        if ret:
            logging.error('Mail, failed recipients:', ', '.join(ret.keys()))
    else:
        logging.error('Mail error: %s', ret)
Example #30
0
def send_mail_from_note(note,
                        smtp_host,
                        smtp_port,
                        smtp_login,
                        smtp_password,
                        smtp_mode,
                        sender,
                        to,
                        debug=False,
                        verbose=False):

    counter = 1
    resources = {}
    images = []
    if note.resources:
        for r in note.resources:
            k = r.data.bodyHash.encode('hex')
            fn = '%.2i.%s' % (counter, mimetypes.guess_extension(r.mime)[1:])
            resources[k] = 'cid:' + fn
            a, b = r.mime.split('/')
            images.append((r.data.body, a, b, fn, None))
            counter += 1

    text_content = PlainTextOfENML(note.content)
    html_content = HTMLOfENML(note.content, resources)
    title = note.title
    #title = 'La note de %sh' % datetime.now().strftime('%H')

    try:
        payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(
            sender=sender,
            recipients=to,
            subject=title,
            default_charset='utf-8',
            text=(text_content, 'utf-8'),
            html=(html_content, 'utf-8'),
            attachments=None,
            embeddeds=images,
        )
        #headers=(('Reply-To', '*****@*****.**' % str(note.guid)), ))

        ret = pyzmail.send_mail(payload=payload,
                                mail_from=mail_from,
                                rcpt_to=rcpt_to,
                                smtp_host=smtp_host,
                                smtp_port=smtp_port,
                                smtp_mode=smtp_mode,
                                smtp_login=smtp_login,
                                smtp_password=smtp_password)

        if isinstance(ret, dict):
            if ret:
                if verbose:
                    print >> sys.stderr, 'failed recipients:', ', '.join(
                        ret.keys())
            else:
                if verbose:
                    print >> sys.stderr, 'success'
        else:
            if verbose:
                print >> sys.stderr, 'error:', ret

    except Exception, e:
        raise
        return 1
Example #31
0
def send_email(sender_sn, receiver_email, html_content="", text_content=""):
    subject=sender_sn + " sent you a message"

    print 'sending email to ', receiver_email

    msg=MIMEMultipart('alternative')
    msg['Subject']=subject
    msg['From']='Spriggle <' +_SENDER +'>'
    msg['To']=receiver_email

    msg.attach(MIMEText(text_content, 'plain'))
    msg.attach(MIMEText(html_content, 'html'))

    try:
        print 'trying local smtp'
        smtpconn=smtplib.SMTP('localhost')
        smtpconn.sendmail(_SENDER, receiver_email, msg.as_string())
        smtpconn.quit()
        #print 'successfully sent email from smtp:localhost'
    except Exception:
        try:
            print 'trying remote smtp'
            sender=(sender_sn, '*****@*****.**')
            recipients=[msg['To']]
            prefered_encoding='iso-8859-1'
            text_encoding='iso-8859-1'
        
            #todo:tony:add external settings to avoid them being in src ctrl 
            smtp_host='smtp.gmail.com'
            smtp_port=587
            smtp_mode='tls'
            smtp_login='******'
            smtp_password=None 
         
            payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
                    sender, \
                    recipients, \
                    subject, \
                    prefered_encoding, \
                    (text_content, text_encoding), \
                    html=None, \
                    attachments=None)
        
            #print 'text content', text_content
            #print 'html content', html_content 
            #print 'payload', payload
         
            ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \
                    smtp_port=smtp_port, smtp_mode=smtp_mode, \
                    smtp_login=smtp_login, smtp_password=smtp_password)
    
            if isinstance(ret, dict):
                if ret:
                    print 'failed recipients:', ', '.join(ret.keys())
                else:
                    print 'successfully sent email from smtp:remotehost'
            else:
                print 'error:', ret

        except Exception:
            print "error sending email to " + receiver_email