Ejemplo n.º 1
0
def send(to_email, subject, content):
    """
    Send an email.

    :param tuple to_email: email recipient address and name
    :param basestring subject: email subject
    :param basestring content: email content
    """
    if not get_secret('sendgrid_key'):
        # This is a test machine
        return

    try:
        if to_email[0].endswith('@gmail.com'):
            sg = sendgrid.SendGridAPIClient(apikey=get_secret('sendgrid_key'))
            content = Content('text/plain', content)
            mail = Mail(Email(*from_email), subject, Email(to_email[0]),
                        content)
            sg.client.mail.send.post(request_body=mail.get())
        else:
            conn = SMTP('127.0.0.1', 25)
            mail = Envelope(to_addr=to_email[0],
                            from_addr=from_email,
                            subject=subject,
                            text_body=content)
            conn.send(mail)
    except Exception:
        traceback.print_exc()
Ejemplo n.º 2
0
    def emailers(self, from_, to_, subject_, body_):
        envelope = Envelope(from_addr=from_,to_addr=to_,subject=subject_,text_body=body_)

        #TODO add password hashing
        smtpconn = SMTP(host='mail.nikitph.com',port=26,login='******',password='******')
        print(smtpconn.is_connected)
        smtpconn.send(envelope)
Ejemplo n.º 3
0
    def emailers(self, from_, to_, subject_, body_):
        envelope = Envelope(from_addr=from_,to_addr=to_,subject=subject_,text_body=body_)

        #TODO add password hashing
        smtpconn = SMTP(host='mail.nikitph.com',port=26,login='******',password=)
        print(smtpconn.is_connected)
        smtpconn.send(envelope)
Ejemplo n.º 4
0
def main(*args):
    parser = SaltKeyOptionParser()
    parser.parse_args()
    opts = parser.config
    key = Key(opts)
    my_opts = opts['destroy_vm_reminder']
    key_list = key.name_match(my_opts['key_glob'])

    vms = {}
    rxp = re.compile(my_opts['key_regexp'])
    for status, keys in key_list.items():
        for key in keys:
            m = rxp.match(key)
            if m:
                user = m.group("user")
                if user not in vms:
                    vms[user] = []
                vms[user].append(key)

    smtp = SMTP(**my_opts['email']['smtp'])
    template = Template(my_opts['email']['message_template'])

    for user, keys in vms.items():

        res = requests.get(
            ("{prefix}/securityRealm/user/{user}/api/json").format(
                prefix=my_opts['jenkins']['prefix'], user=user),
            auth=(my_opts['jenkins']['username'],
                  my_opts['jenkins']['api_token']))
        data = json.loads(res.content)
        name = data['fullName']
        email = ''
        for property in data['property']:
            if 'address' in property:
                email = property['address']
                break

        message = template.render(
            name=name,
            vms=keys,
            url="{prefix}/job/{job_name}/build?delay=0sec".format(
                prefix=my_opts['jenkins']['prefix'],
                job_name=my_opts['destroy_job']))

        envelope = Envelope(
            from_addr=my_opts['email']['from'],
            to_addr=(email, name),
            subject=my_opts['email']['subject'],
            text_body=message,
        )
        smtp.send(envelope)
Ejemplo n.º 5
0
def main(*args):
    parser = SaltKeyOptionParser()
    parser.parse_args()
    opts = parser.config
    key = Key(opts)
    my_opts = opts['destroy_vm_reminder']
    key_list = key.name_match(my_opts['key_glob'])

    vms = {}
    rxp = re.compile(my_opts['key_regexp'])
    for status, keys in key_list.items():
        for key in keys:
            m = rxp.match(key)
            if m:
                user = m.group("user")
                if user not in vms:
                    vms[user] = []
                vms[user].append(key)

    smtp = SMTP(**my_opts['email']['smtp'])
    template = Template(my_opts['email']['message_template'])

    for user, keys in vms.items():

        res = requests.get(("{prefix}/securityRealm/user/{user}/api/json").format(
            prefix=my_opts['jenkins']['prefix'], user=user),
                           auth=(my_opts['jenkins']['username'],
                                 my_opts['jenkins']['api_token']))
        data = json.loads(res.content)
        name = data['fullName']
        email = ''
        for property in data['property']:
            if 'address' in property:
                email = property['address']
                break

        message = template.render(
            name=name, vms=keys,
            url="{prefix}/job/{job_name}/build?delay=0sec".format(
                prefix=my_opts['jenkins']['prefix'],
                job_name=my_opts['destroy_job']))

        envelope = Envelope(
            from_addr=my_opts['email']['from'],
            to_addr=(email, name),
            subject=my_opts['email']['subject'],
            text_body = message,
        )
        smtp.send(envelope)
Ejemplo n.º 6
0
 def send(self, links):
     self.connection = SMTP(port=self.port,
                            host=self.host,
                            tls=self.tls,
                            login=self.login,
                            password=self.password)
     envelope = Envelope(from_addr=(self.sender, u'Notification'),
                         to_addr=(self.recipient),
                         subject=self.subject,
                         text_body=u"Nowy link:\n {}".format(
                             "\n".join(links)))
     envelope.add_header('Date', email.utils.formatdate(localtime=True))
     envelope.add_header('In-Reply-To', '*****@*****.**')
     try:
         self.connection.send(envelope)
         print('Email sent.')
     except Exception as e:
         print(
             'Could not send email with links: {}'.format(','.join(links)),
             e)
Ejemplo n.º 7
0
class notification:
    def __init__(self, config_path='./config.ini'):
        self.get_config(config_path)

    def get_config(self, config_path='./config.ini'):
        config = configparser.ConfigParser()
        config.read(config_path)
        self.login = config['email']['login']
        self.password = config['email']['password']
        self.host = config['email']['host']
        self.port = config['email']['port']
        self.tls = config['email']['tls']
        self.subject = config['notification']['subject']
        self.recipient = config['notification']['recipient']
        self.sender = config['notification']['sender']

    def send(self, links):
        self.connection = SMTP(port=self.port,
                               host=self.host,
                               tls=self.tls,
                               login=self.login,
                               password=self.password)
        envelope = Envelope(from_addr=(self.sender, u'Notification'),
                            to_addr=(self.recipient),
                            subject=self.subject,
                            text_body=u"Nowy link:\n {}".format(
                                "\n".join(links)))
        envelope.add_header('Date', email.utils.formatdate(localtime=True))
        envelope.add_header('In-Reply-To', '*****@*****.**')
        try:
            self.connection.send(envelope)
            print('Email sent.')
        except Exception as e:
            print(
                'Could not send email with links: {}'.format(','.join(links)),
                e)
random_num = random.randint(1, 10000)

if conf.file_source.find('localhost:') == 0:
    test_sourcedir = conf.file_source[len('localhost:'):]
    print "Writing test file to ", test_sourcedir
else:
    "Need to set source to localhost for automated testing."

dirutils.ensure_dir(test_sourcedir)
filename_to_send = 'foo' + str(random_num) + '.txt'
with open(os.path.join(test_sourcedir, filename_to_send), 'wb') as f:
    f.write('Hello, world!')


msg = Envelope(to_addr=(conf.account_username, conf.account_username),
               from_addr=(conf.account_username, conf.account_username),
               subject=" ".join(conf.magic_subject_words + [filename_to_send]),
               text_body='Hello world')

print "Msg", msg


gmail = SMTP(host='smtp.googlemail.com', port=587,
             login=conf.account_username, password=conf.account_pass, tls=True)
# gmail = GMailSMTP(login=account_username, password=account_pass)
print "Connected?"
# print gmail

gmail.send(msg)
print "Sent!"
Ejemplo n.º 9
0
from envelopes import Envelope, SMTP
import envelopes.connstack
from flask import Flask, jsonify
import os

app = Flask(__name__)
app.config['DEBUG'] = True
conn = SMTP('127.0.0.1', 1025)

@app.before_request
def app_before_request():
    envelopes.connstack.push_connection(conn)

@app.after_request
def app_after_request(response):
    envelopes.connstack.pop_connection()
    return response

@app.route('/mail', methods=['POST'])
def post_mail():
    envelope = Envelope(
        from_addr='%s@localhost' % os.getlogin(),
        to_addr='%s@localhost' % os.getlogin(),
        subject='Envelopes in Flask demo',
        text_body="I'm a helicopter!"
    )

    smtp = envelopes.connstack.get_current_connection()
    smtp.send(envelope)
    return jsonify(dict(status='ok'))
Ejemplo n.º 10
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "liulixiang"

from envelopes import Envelope, SMTP, GMailSMTP

# 构造envelop
envelope = Envelope(
    from_addr=("*****@*****.**", "理想"),
    to_addr=("*****@*****.**", "刘理想"),
    subject="envelope库的使用",
    text_body="envelope是一个python库,可以用来发送邮件",
)
# 添加附件
envelope.add_attachment("/Users/liulixiang/Downloads/1.png")

# 发送邮件
# 发送邮件方法1
envelope.send("smtp.qq.com", login="******", password="******")

# 发送邮件方法2
qq = SMTP(host="smtp.qq.com", login="******", password="******")
qq.send(envelope)
Ejemplo n.º 11
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'liulixiang'

from envelopes import Envelope, SMTP, GMailSMTP

#构造envelop
envelope = Envelope(from_addr=('*****@*****.**', '理想'),
                    to_addr=('*****@*****.**', '刘理想'),
                    subject='envelope库的使用',
                    text_body='envelope是一个python库,可以用来发送邮件')
#添加附件
envelope.add_attachment('/Users/liulixiang/Downloads/1.png')

#发送邮件
#发送邮件方法1
envelope.send('smtp.qq.com', login='******', password='******')

#发送邮件方法2
qq = SMTP(host='smtp.qq.com', login='******', password='******')
qq.send(envelope)