コード例 #1
0
    def send(self, from_address, to_address, subject, body=None, html=True):
        try:
            message = Message(
                From=from_address,
                To=to_address,
                charset=self.charset
            )

            if body is None:
                body = ''
            self.body = body

            message.Subject = "%s - %s" % (self.subject_prefix, subject)
            message.Html = self.body
            message.Body = self.body
        except Exception as e:
            log.exception('[scaffold_mailer] - Failed to create message object for mailer')
            return False

        try:
            sender = Mailer(
                host=self.config.get('host'),
                port=self.config.get('port'),
                use_tls=self.config.get('use_tls', False),
                use_ssl=True,
                usr=self.config.get('username'),
                pwd=self.config.get('password'))
            sender.send(message)
        except Exception as e:
            log.exception('[scaffold_mailer] - Failed to connect to smtp sever and send message with subject: %s' % message.Subject)
            return False
        return True
コード例 #2
0
ファイル: alerts.py プロジェクト: jwplayer/rssalertbot
def alert_email(feed, cfg, entry):
    """Sends alert via email.

    Args:
        feed (:py:class:`Feed`): the feed
        cfg (dict):              output config
        entry (dict):            the feed entry
    """
    logger = logging.LoggerAdapter(log, extra = {
        'feed':  feed.name,
        'group': feed.group['name'],
    })

    logger.debug(f"[{feed.name}] Alerting email: {entry.title}")

    description = strip_html(entry.description)

    try:
        smtp = Mailer(host=cfg['server'])
        message = Message(charset="utf-8", From=cfg['from'], To=cfg['to'],
                          Subject = f"{feed.group['name']} Alert: ({feed.name}) {entry.title}")
        message.Body = f"Feed: {feed.name}\nDate: {entry.datestring}\n\n{description}"
        message.header('X-Mailer', 'rssalertbot')
        smtp.send(message)

    except Exception:
        logger.exception(f"[{feed.name}] Error sending mail")
コード例 #3
0
ファイル: mailman.py プロジェクト: cychenyin/windmill
def sendmail(mailto, subject, html='', text='', textfile='', htmlfile='', attachments=''):
    '''send mail'''
    if not mailto:
        print 'Error: Empty mailto address.\n'
        return

    mailto = [sb.strip() for sb in mailto.split(',')]
    if attachments:
        attachments = [att.strip() for att in attachments.split(',')] 
    else:
        attachments = []
    
    #USERNAME = hostname()
    subject = "%s-[%s]" % ( subject, hostname())

    message = Message(From=USERNAME, To=mailto, Subject=subject, attachments=attachments)
    message.Body = text
    message.Html = html
    message.charset = 'utf8'
    try:
        if htmlfile:
            message.Html += open(htmlfile, 'r').read()
        if textfile:
            message.Body += open(textfile, 'r').read()
    except IOError:
        pass

    for att in attachments:
        message.attach(att)

    sender = Mailer(SERVER,port=465, use_tls=True, usr=USERNAME, pwd=PASSWD)
    #sender = Mailer(SERVER)
    #sender.login(USERNAME, PASSWD)
    sender.send(message)
コード例 #4
0
ファイル: email_man.py プロジェクト: ntohidi/flask-login
def send_email(user_email="", html="", subject=""):
    msg = Message(From="Cool App", To=user_email, charset="utf-8")
    msg.Subject = subject
    msg.Body = subject
    msg.Html = html

    return email_sender(msg)
コード例 #5
0
ファイル: email_man.py プロジェクト: ntohidi/flask-login
def send_email_with_file(user_email="", html="", subject="", file_path=""):
    msg = Message(From="Cool App", To=user_email, charset="utf-8")
    msg.Subject = subject
    msg.Body = subject
    msg.Html = html
    msg.attach(file_path)

    return email_sender(msg)
コード例 #6
0
ファイル: mappings.py プロジェクト: AcrDijon/trombi
 def send_reset_email(self):
     self.token = os.urandom(32).encode('hex')
     sender = Mailer('localhost', port=25)
     msg = Message(From="*****@*****.**", To=[self.email],
                   charset="utf-8")
     msg.Subject = u'Accès trombinoscope ACR'
     msg.Body = _BODY % (unicode(self.token), unicode(self.login))
     sender.send([msg])
コード例 #7
0
 def send(self):
     """Send the email described by this object."""
     message = Message(From=self.sender,
                       To=self.to,
                       charset="utf-8")
     message.Subject = self.subject
     message.Body = self.body
     mailer = Mailer(self.smtp_server)
     mailer.send(message)
コード例 #8
0
ファイル: statusemail.py プロジェクト: WeszNL/autorsyncbackup
 def _send(self, subject, htmlbody):
     for to in config().backupmailrecipients:
         logger().info("INFO: Sent backup report to [%s] via SMTP:%s" % (to, config().smtphost))
         message = Message(From=config().backupmailfrom, To=to, charset="utf-8")
         message.Subject = subject
         message.Html = htmlbody
         message.Body = """This is an HTML e-mail with the backup overview, please use a HTML enabled e-mail client."""
         sender = Mailer(config().smtphost)
         sender.send(message)
コード例 #9
0
def send_email(sender=REPORT_SENDER, recipient=REPORT_RECIPIENTS, subject='Reports finished', body=None):
    try:
        message = Message(From=sender, To=recipient, Subject=subject)
        message.Body = body

        sender = Mailer(EMAIL_RELAY)
        sender.send(message)
    except Exception as e:
        get_logger().error(e)
コード例 #10
0
    def emailSender(self):
        message = Message(From="*****@*****.**",
                          To=["*****@*****.**"],
                          Subject="University Management System")
        message.Body = """UMS deepanshu ahuja"""
        # message.attach("kitty.jpg")

        sender = Mailer('smtp.example.com')
        sender.send(message)
コード例 #11
0
 def _send(self, subject, htmlbody, textbody):
     for to in config().backupmailrecipients:
         logger().info("Sent backup report to [%s] via SMTP:%s" % (to, config().smtphost))
         message = Message(From=config().backupmailfrom, To=to, charset="utf-8")
         message.Subject = subject
         message.Html = htmlbody
         message.Body = textbody
         sender = Mailer(config().smtphost)
         sender.send(message)
コード例 #12
0
ファイル: app_globals.py プロジェクト: quentinmit/bluechips
 def handle_notification(self, users, subject, body):
     "Send a notification email."
     recipients = [u.email for u in users if u.email is not None]
     if len(recipients) > 0:
         msg = Message(From=config.get('mailer.from', 'root@localhost'),
                       To=recipients,
                       charset='utf-8')
         msg.Subject = ("BlueChips: %s" % subject).encode('utf-8')
         msg.Body = body
         self.send_message(msg)
コード例 #13
0
ファイル: app_globals.py プロジェクト: andersk/bluechips
 def handle_notification(self, users, subject, body):
     "Send a notification email."
     recipients = [u.email for u in users if u.email is not None]
     if len(recipients) > 0:
         msg = Message(From=config.get('mailer.from',
                                       'root@localhost'),
                       To=recipients)
         msg.Subject = "BlueChips: %s" % subject
         msg.Body = body
         self.send_message(msg)
コード例 #14
0
ファイル: emailer.py プロジェクト: CarbonComputed/flotag
def verify_email(user):
#     logger.debug("Generated email verification link: " + user.reg_id)
#     if not user.active:
    message = Message(From="*****@*****.**",To="*****@*****.**",charset="utf-8")
    message.Subject = "Flotag Email Verification"
    message.Html = """This email uses <strong>Complete Flotag Registration</strong>!"""
    message.Body = """Flotag Registration"""
    
    sender = Mailer('127.0.0.1')
    sender.send(message)
コード例 #15
0
    def send(self, from_address, to_address, subject, body='', html=True):
        message = Message(From="*****@*****.**",
                          To=to_address,
                          charset=self.charset)
        message.Subject = "%sAn HTML Email" % self.subject_prefix
        message.Html = body
        message.Body = body

        sender = Mailer(self.host)
        sender.send(message)
コード例 #16
0
ファイル: sendmail.py プロジェクト: adsame/api
    def send_mail(self):
    
        message =  Message(From=self.fr,
                    To=self.to,
                    Subject=self.sub,
                    Charset='utf8')
	message.Body = self.body

        sender = Mailer(host=self.server,usr=self.usr,pwd=self.pwd)
        sender.send(message)
コード例 #17
0
    def send(self):
        message = Message(From=self.render(self.sender),
                          To=self.render(self.to),
                          Subject=self.render(self.subject),
                          charset='utf-8')
        message.Body = self.render_file(self.template)
        message.Html = self.render_file(self.html_template)

        mailer = Mailer(**self.mailer_settings)
        mailer.send(message)
コード例 #18
0
ファイル: video.py プロジェクト: rickysaltzer/lolock
def send_email(image):
	# Format email message
	message = Message(From=MAIL_FROM,To=MAIL_TO)
	message.Subject = MAIL_SUBJECT
	message.Html = MAIL_HTML
	message.Body = MAIL_BODY
	message.attach(image)

	# Send message to SMTP server
	sender = Mailer(SMTP_HOST)
	sender.send(message)
コード例 #19
0
def send_email(from_email, to_email_list, subject, html, smtp_host, smtp_port=587, username=None, password=None):
    message = Message(From=from_email, To=to_email_list, charset='utf-8')
    # Keep from creating threads in gmail...
    message.Subject = "{} -- {}".format(subject, datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
    message.Html = html.encode('utf-8')
    message.Body = 'See the HTML!'

    sender = Mailer(host=smtp_host, port=smtp_port, use_tls=True, usr=username, pwd=password)
    if username is not None:
        sender.login(username, password)
    sender.send(message)
コード例 #20
0
ファイル: notify.py プロジェクト: neybar/icloud-drive-docker
def build_message(email):
    message = Message()
    message.To = email
    message.From = "icloud-drive-docker <" + email + ">"
    message.Date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
    message.Subject = "icloud-drive-docker: Two step authentication required"
    message.Body = """Two-step authentication for iCloud Drive (Docker) is required.
Please login to your server and authenticate.  Eg:
`docker exec -it icloud-drive /bin/sh -c "icloud --username=<icloud-username>"`."""

    return message
コード例 #21
0
def main():
    rev = test_rev.get_rev('./')

    message = Message(From="*****@*****.**",
                      To="*****@*****.**",
                      charset="utf-8")
    message.Subject = "HYMLS test results for revision " + rev
    message.Body = dataparser.compare(rev)

    sender = Mailer('smtp.rug.nl')
    sender.send(message)
コード例 #22
0
def send_email(image):
    # Format email message
    message = Message(From=MAIL_FROM, To=MAIL_TO)
    message.Subject = MAIL_SUBJECT
    message.Html = MAIL_HTML
    message.Body = MAIL_BODY
    message.attach(image)

    # Send message to SMTP server
    sender = Mailer(SMTP_HOST)
    sender.send(message)
コード例 #23
0
ファイル: main.py プロジェクト: mopsalarm/feedbacky
    def send_feedback_mail(version, username, feedback, logcat):
        # noinspection PyBroadException
        try:
            msg = Message(From=args.user, To=args.receiver, charset="utf8")
            msg.Subject = u"Feedback {} ({})".format(version, username)
            msg.Body = u"User: {0} http://pr0gramm.com/user/{0}\nFeedback: {1}\n\nLogcat: {2}\n".format(username, feedback, logcat)

            mailer = Mailer(args.host, port=587, use_tls=True, usr=args.user, pwd=args.password)
            mailer.send(msg)

        except:
            traceback.print_exc()
コード例 #24
0
ファイル: emailer.py プロジェクト: CarbonComputed/flotag
def verify_email(user):
    #     logger.debug("Generated email verification link: " + user.reg_id)
    #     if not user.active:
    message = Message(From="*****@*****.**",
                      To="*****@*****.**",
                      charset="utf-8")
    message.Subject = "Flotag Email Verification"
    message.Html = """This email uses <strong>Complete Flotag Registration</strong>!"""
    message.Body = """Flotag Registration"""

    sender = Mailer('127.0.0.1')
    sender.send(message)
コード例 #25
0
ファイル: email.py プロジェクト: alin23/spfy
 def send_auth_email(email, auth_url):
     logger.info("Login here to use Spotify API: %s", auth_url)
     mailer = Mailer(**config.email)
     # pylint: disable=no-member
     html_content = LOGIN_HTML.read_text().replace(
         "SPOTIFY_AUTHENTICATION_URL", auth_url
     )
     message = Message(From=config.email.usr or email, To=email, charset="utf-8")
     message.Subject = "Spotify API Authentication"
     message.Html = html_content
     message.Body = f"Login here to use Spotify API: {auth_url}"
     mailer.send(message)
コード例 #26
0
 def _send(self, subject, htmlbody):
     for to in config().backupmailrecipients:
         logger().info("Sent backup report to [%s] via SMTP:%s" %
                       (to, config().smtphost))
         message = Message(From=config().backupmailfrom,
                           To=to,
                           charset="utf-8")
         message.Subject = subject
         message.Html = htmlbody
         message.Body = """This is an HTML e-mail with the backup overview, please use a HTML enabled e-mail client."""
         sender = Mailer(config().smtphost)
         sender.send(message)
コード例 #27
0
 def _send(self, subject, htmlbody, textbody):
     for to in config().backupmailrecipients:
         logger().info("Sent backup report to [%s] via SMTP:%s" %
                       (to, config().smtphost))
         message = Message(From=config().backupmailfrom,
                           To=to,
                           charset="utf-8")
         message.Subject = subject
         message.Html = htmlbody
         message.Body = textbody
         sender = Mailer(config().smtphost)
         sender.send(message)
コード例 #28
0
def sendGalaxyNotifyMail(galaxyID, galaxyName, user):
    # send message
    message = Message(
        From="\"Galaxy Harvester Registration\" <*****@*****.**>",
        To="*****@*****.**")
    message.Subject = "New Galaxy Submitted For Review"
    link = "http://galaxyharvester.net/galaxy.py/{0}".format(galaxyID)
    message.Body = user + " has submitted a new galaxy for review.\n\n" + link
    message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>" + user + " has submitted a new galaxy for review.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Review</div></a><br/>or copy and paste link: " + link + "</p>"
    mailer = Mailer(mailInfo.MAIL_HOST)
    mailer.login(mailInfo.MAIL_USER, mailInfo.MAIL_PASS)
    mailer.send(message)
    return 'email sent'
コード例 #29
0
 def test(self):
     try:
         message = Message(
             From=self.email,
             to='*****@*****.**',
             charset='utf-8',
         )
         message.Subject = 'Testando...'
         message.Body = '... tudo OK'
         self.mailer.send(message)
     except:
         return False
     return True
コード例 #30
0
def sendVerificationMail(user, address, code):
    # send message
    message = Message(From="\"Galaxy Harvester Activation\" <{0}>".format(
        mailInfo.REGMAIL_USER),
                      To=address)
    message.Subject = "Galaxy Harvester Account Verification"
    link = "http://galaxyharvester.net/verifyUser.py?vc={0}".format(code)
    message.Body = "Hello " + user + ",\n\nYou have created a new account on galaxyharvester.net using this email address.  Before you can use your new account, you must verify this email with us by clicking the link below.  If the link does not work, please copy the link and paste it into your browser address box.\n\n" + link + "\n\nThanks,\n-Galaxy Harvester Administrator\n"
    message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello " + user + ",</p><br/><p>You have created a new account on galaxyharvester.net using this email address.  Before you can use your new account, you must verify this email with us by clicking the link below.  If the link does not work, please copy the link and paste it into your browser address box.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Verify</div></a><br/>or copy and paste link: " + link + "</p><br/><p>Thanks,</p><p>-Galaxy Harvester Administrator</p>"
    mailer = Mailer(mailInfo.MAIL_HOST)
    mailer.login(mailInfo.REGMAIL_USER, mailInfo.MAIL_PASS)
    mailer.send(message)
    return 'email sent'
コード例 #31
0
ファイル: __init__.py プロジェクト: berdosi/multicorn_smtp
    def insert(self, values):
        """When an INSERT statement is set, send a mail with the 
            from, to, subject, html_body and body values."""
        message = Message(From=values["from"],
                          To=values["to"],
                          charset="utf-8")
        message.Subject = values["subject"]

        message.Html = values["html_body"] or None
        message.Body = values["body"]

        sender = Mailer('localhost')
        sender.send(message)
コード例 #32
0
ファイル: mail.py プロジェクト: hs634/digestive
    def __init__(self, from_email, to_emails, subject, html, mailer=None):
        if mailer is None:
            mailer = Mailer(host='localhost', port=1025)

        for to_email in to_emails:
            message = Message(From=from_email,
                              To=to_email,
                              charset="utf-8")
            message.Subject = subject
            message.Html = html
            message.Body = """Digestive doesn't support non-html emails. Sorry!"""

            sender = mailer
            sender.send(message)
コード例 #33
0
    def notify(self):
        """ publishs the rss feed at the given url
            @param[in] fname
            @param[in] url
        """
        if not self.notifications:
            return

        message = Message(From=self.sender,
                          To=self.recipients,
                          Subject=self.subject)
        message.Body = '\n\n'.join( map(self._formatNotification, 
                                        self.notifications) )
        Mailer(self.mailhost).send(message)
        self.notifiers = []
コード例 #34
0
def newemail(error):
    #Currently setup for gmail
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login("youremail", "YOURPASSWORD")
    fp = open(outputTxt)
    message = Message(From="SENDEREMAIL",
                      To="RECIEVEREMAIL",
                      charset="utf-8")
    message.Subject = 'Service Validation has FAILED!!!'
    message.Body ='\n' + error + '\n'.join(fp.readlines())
    #message.Body = 'Hello, \n\n  The validation job has FAILED for Web Service Validation!!!  Please refer to the error below for failed results\n'.join(fp.readlines())
    fp.close()
    server.sendmail("YOUREMAIL", "RECEIVERSEMAIL", message.as_string())
    server.quit()
コード例 #35
0
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle):
	# Don't try to send mail if we exceeded quota within last hour
	lastFailureTime = datetime(2000, 1, 1, 12)
	currentTime = datetime.fromtimestamp(time.time())
	timeSinceFailure = currentTime - lastFailureTime
	try:
		f = open("last_email_failure.txt")
		lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S")
		f.close()
		timeSinceFailure = currentTime - lastFailureTime
	except IOError as e:
		sys.stdout.write("No last failure time\n")

	if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
		return 1

	# look up the user email
	cursor = conn.cursor()
	cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';")
	row = cursor.fetchone()
	if row == None:
		result = "bad username"
	else:
		email = row[0]
		if (email.find("@") > -1):
			# send message
			message = Message(From="\"Galaxy Harvester Alerts\" <*****@*****.**>",To=email)
			message.Subject = "".join(("Galaxy Harvester ", alertTitle))
			message.Body = "".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n"))
			message.Html = "".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>"))
			mailer = Mailer(mailInfo.MAIL_HOST)
			mailer.login(mailInfo.ALERTMAIL_USER, mailInfo.MAIL_PASS)
			try:
				mailer.send(message)
				result = 'email sent'
			except SMTPRecipientsRefused as e:
				result = 'email failed'
				sys.stderr.write('Email failed - ' + str(e))
				trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"))

			# update alert status
			if ( result == 'email sent' ):
				cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';')
		else:
			result = 'Invalid email.'


	cursor.close()
コード例 #36
0
ファイル: utils.py プロジェクト: johnmontero/o-jigi
    def send_mails(self, message=None):

        sender = Mailer(host=self.config.get(MAILER, HOST),
                        port=int(self.config.get(MAILER, PORT)),
                        usr=self.config.get(MAILER, USERNAME),
                        pwd=self.config.get(MAILER, PASSWORD))
        subject = self.config_repo.get(self.branch, SUBJECT)
        subject = subject.format(repository=self.repository, branch=self.branch)

        for mail in self.mails:
            msg = Message(From=self.config_repo.get(self.branch, FROM),
                          To=mail,
                          charset='utf-8')
            msg.Subject = subject
            msg.Body = message
            sender.send(msg)
コード例 #37
0
def send_mail(subject, body):
    asterisk_install = socket.gethostname()
    if options.fromemail == 'asterisk@hostname':
        mail_from = 'asterisk@' + socket.getfqdn()
    else:
        mail_from = options.fromemail
    message = Message(From=mail_from, To=arguments, charset="utf-8")
    message.Subject = '[' + (options.flag or asterisk_install) + '] ' + subject
    message.Body = u'Hostname : %s\n\n' % asterisk_install + body + u"\n-- \nAutomatic e-mail sent by the monitoring script check_sip_trunks.py. Do not reply."
    sender = Mailer(options.smtp)
    try:
        sender.send(message)
        if not options.silent:
            print "Mail sent"
    except Exception, e:
        print "CANNOT send e-mail : %s" % str(e)
コード例 #38
0
def send_mail(subject, body):
    asterisk_install = socket.gethostname()
    if options.fromemail == 'asterisk@hostname':
        mail_from = 'asterisk@' + socket.getfqdn()
    else:
        mail_from = options.fromemail
    message = Message(From=mail_from, To=arguments, charset="utf-8")
    message.Subject = '[' + (options.flag or asterisk_install) + '] ' + subject
    message.Body = u'Hostname : %s\n\n' % asterisk_install + body + u"\n-- \nAutomatic e-mail sent by the monitoring script check_sip_trunks.py. Do not reply."
    sender = Mailer(options.smtp)
    try:
        sender.send(message)
        if not options.silent:
            print "Mail sent"
    except Exception, e:
        print "CANNOT send e-mail : %s" % str(e)
コード例 #39
0
ファイル: send_email.py プロジェクト: JaneliaSciComp/msg
def send_email(email_host, to, cc, subject, body):
    """send the PDF as an email """   
    def tolist(email_str):
        email_str = email_str or ''
        email_str = email_str.replace(',',';')
        if ';' in email_str:
            return email_str.split(';')
        else:
            return [email_str]
    message = Message(From=tolist(to)[0], To=tolist(to), CC=tolist(cc), charset="utf-8")
    message.Subject = subject
    #message.Html = """This email uses <strong>HTML</strong>!"""
    message.Body = body
    #message.attach(filename=report_path, cid="Scheduled_Report.pdf")
    sender = Mailer(email_host)
    sender.send(message)
コード例 #40
0
ファイル: fabfile.py プロジェクト: ctsit/redman
def send_email(email_props, content):
    """ Helper for sending emails"""
    p = email_props
    mess = Message(charset="utf-8")
    mess.From = p.email_sender
    mess.To = p.email_recipient
    mess.Subject = p.email_subject
    mess.Html = content
    mess.Body = "Please enable HTML in your client to view this message."
    sender = Mailer(p.email_server)

    try:
        sender.send(mess)
        logger.info("Email [{}] was sent to: {}".format(mess.Subject, mess.To))
    except Exception as exc:
        logger.error("Problem sending email [{}] to [{}]: {}"
                     .format(p.email_subject, p.email_recipient, exc))
コード例 #41
0
ファイル: userupdate.py プロジェクト: lqpp/lqfb_userupdate
def lock_users(db_users):

    con = None

    try:
        con = psycopg2.connect(database=dbname, user="******")
        cur = con.cursor()

        cur.execute("BEGIN")

        logger.info("\n######################################################\nLocked invite codes: ")

        sender = Mailer("127.0.0.1")

        for db_user in db_users:

            # check that invitecode is nonempty
            if db_user[0] != None:

                cur.execute("UPDATE member set (locked, active) = (true,false) where invite_code='" + db_user[0] + "'")

                # send mail to user
                message = Message(
                    From="*****@*****.**",
                    Envelope - From="*****@*****.**",
                    To=db_user[6],
                    Subject="Sperrung LQFB",
                )
                message.Body = """Hi, dein Account ist gesperrt. Haha!"""
                if false:  # TODO: Soll gesendet werden?
                    sender.send(message)

                logger.info(db_user[0])

            else:
                logger.error("Error locking user: Empty invite code: ID=" + str(db_user[1]))

        if options.dryrun:
            cur.execute("ABORT")
        else:
            cur.execute("COMMIT")

    except psycopg2.DatabaseError, e:
        logger.error("DB Error: %s" % e)
        sys.exit(1)
コード例 #42
0
 def enviar(self, email):
     message = Message(
         From=self.email,
         to=email.para_email,
         charset='utf-8',
         # TODO: List-Unsubscribe
         # headers={'List-Unsubscribe': '<{}{}>'.format(
         #     settings.FULL_URL,
         #     reverse('unsubscribe_email', kwargs={'chave': self.emailconfig.chave})
         # )}
     )
     message.Subject = email.assunto
     message.Body = email.corpo
     if email.corpo_html:
         message.Html = email.corpo_html
     self.mailer.send(message)
     email.enviado = timezone.now()
     email.save(update_fields=['enviado'])
コード例 #43
0
def build_email(from_address, to_address, subject, content, attach_rpt=None):
    message = Message()

    message.From = from_address
    message.To = to_address
    # message.CC = cc
    # message.charset = "utf-8"

    message.Subject = subject
    message.Body = content
    if attach_rpt != None:
        message.attach(attach_rpt, mimetype='text/csv', charset='us-ascii')
    # message.attach(attach_pdf, mimetype="application/pdf")
    # message.attach(img_path, cid='image_cid')

    print('message:', message)

    return message
コード例 #44
0
def sendVerificationMail(user, address, code):
    # send message
    message = Message(
        From=
        "\"Galaxy Harvester Registration\" <*****@*****.**>",
        To=address)
    message.Subject = "Galaxy Harvester Email Change Verification"
    link = "http://galaxyharvester.net/verifyUser.py?vc={0}&vt=mail".format(
        code)
    message.Body = "Hello " + user + ",\n\nYou have updated your e-mail address on galaxyharvester.net to this email address.  You must verify this email with us by clicking the link below before the change can be completed.  If the link does not work, please copy the link and paste it into your browser address box.\n\n" + link + "\n\nThanks,\n-Galaxy Harvester Administrator\n"
    message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello " + user + ",</p><br/><p>You have updated your e-mail address on galaxyharvester.net to this email address.  You must verify this email with us by clicking the link below before the change can be completed.  If the link does not work, please copy the link and paste it into your browser address box.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Verify</div></a><br/>or copy and paste link: " + link + "</p><br/><p>Thanks,</p><p>-Galaxy Harvester Administrator</p>"
    mailer = Mailer(mailInfo.MAIL_HOST)
    mailer.login(mailInfo.REGMAIL_USER, mailInfo.MAIL_PASS)
    try:
        mailer.send(message)
    except SMTPRecipientsRefused:
        return 'email not valid'

    return 'email sent'
コード例 #45
0
def sendmail(mailto,
             subject,
             html='',
             text='',
             textfile='',
             htmlfile='',
             attachments=''):
    '''send mail'''
    if not mailto:
        print 'Error: Empty mailto address.\n'
        return

    mailto = [sb.strip() for sb in mailto.split(',')]
    if attachments:
        attachments = [att.strip() for att in attachments.split(',')]
    else:
        attachments = []

    #USERNAME = hostname()
    subject = "%s-[%s]" % (subject, hostname())

    message = Message(From=USERNAME,
                      To=mailto,
                      Subject=subject,
                      attachments=attachments)
    message.Body = text
    message.Html = html
    message.charset = 'utf8'
    try:
        if htmlfile:
            message.Html += open(htmlfile, 'r').read()
        if textfile:
            message.Body += open(textfile, 'r').read()
    except IOError:
        pass

    for att in attachments:
        message.attach(att)

    sender = Mailer(SERVER, port=465, use_tls=True, usr=USERNAME, pwd=PASSWD)
    #sender = Mailer(SERVER)
    #sender.login(USERNAME, PASSWD)
    sender.send(message)
コード例 #46
0
ファイル: emailv2.py プロジェクト: pcleddy/AWS-tools
    def send_email_via_localhost(self):
        message = Message(
            From = self.attrs['email_from'],
            To = self.attrs['email_to'],
            charset = "utf-8"
        )
        message.Subject = self.attrs['subject']
        if 'html' in self.attrs:
            message.Html = self.attrs['html']
        if 'text' in self.attrs:
            message.Body = self.attrs['text']

        m_smtp_server = self.attrs['smtp_server'] if ('smtp_server' in self.attrs) else 'localhost'
        if 'smtp_port' in self.attrs: m_smtp_server = m_smtp_server + ':' + self.attrs['smtp_port']

        sender = Mailer(m_smtp_server)
        try:
            sender.send(message)
        except:
            print('Failed to send email, check smtp server and port')
コード例 #47
0
def send_email(email_host, to, cc, subject, body):
    """send the PDF as an email """
    def tolist(email_str):
        email_str = email_str or ''
        email_str = email_str.replace(',', ';')
        if ';' in email_str:
            return email_str.split(';')
        else:
            return [email_str]

    message = Message(From=tolist(to)[0],
                      To=tolist(to),
                      CC=tolist(cc),
                      charset="utf-8")
    message.Subject = subject
    #message.Html = """This email uses <strong>HTML</strong>!"""
    message.Body = body
    #message.attach(filename=report_path, cid="Scheduled_Report.pdf")
    sender = Mailer(email_host)
    sender.send(message)
コード例 #48
0
def alert_email(feed, cfg, entry):
    """Sends alert via email.

    Args:
        feed (:py:class:`Feed`): the feed
        cfg (dict):              output config
        entry (dict):            the feed entry
    """
    log.debug(f"Alerting email: {entry.title}")

    description = strip_html(entry.description)

    smtp = Mailer(host=cfg['server'])
    message = Message(
        charset="utf-8",
        From=cfg['from'],
        To=cfg['to'],
        Subject=f"{feed.group['name']} Alert: ({feed.name}) {entry.title}")
    message.Body = f"Feed: {feed.name}\nDate: {entry.datestring}\n\n{description}"
    message.header('X-Mailer', 'rssalertbot')
    smtp.send(message)
コード例 #49
0
ファイル: wuclient.py プロジェクト: rob4lderman/ari-vetmate
def sendNotificationViaGmail( fromAddr, fromPass, toAddr, subject, msg):

    logTrace("sendNotificationViaGmail: fromAddr:", fromAddr,
                                       "fromPass:"******"x" * len(fromPass) ),
                                       "toAddr:", toAddr,
                                       "subject:", subject,
                                       "msg:", msg )

    message = Message(From=fromAddr,
                      To=toAddr)

    message.Subject = subject
    message.Body = msg
    # message.Html = "".join( emailLinesHtml )

    sender = Mailer('smtp.gmail.com', 
                     port=587,
                     use_tls=True, 
                     usr=fromAddr,
                     pwd=fromPass )
    sender.send(message)
コード例 #50
0
ファイル: mailing.py プロジェクト: pupizoid/Clothes
def send_register_mail(user, pwd):
    message = Message()
    message.From = 'no-reply'
    message.Body = "Ваш пароль: %s" % pwd
    message.To = user['email']
    message.Subject = 'Регистрация в системе'
    try:
        sender.send(message)
        return True
    except (
        smtplib.SMTPAuthenticationError,
        smtplib.SMTPDataError,
        smtplib.SMTPConnectError,
        smtplib.SMTPRecipientsRefused,
        smtplib.SMTPSenderRefused,
        smtplib.SMTPResponseException,
        smtplib.SMTPServerDisconnected,
        smtplib.SMTPHeloError,
        smtplib.SMTPException
    ) as e:
        print(e)
        return False
コード例 #51
0
ファイル: mail.py プロジェクト: CrabbyPete/rxmed
def send_email(name, email, mess):
    """ Send new password to user
    """

    mail = Mailer(host=EMAIL['host'],
                  port=EMAIL['port'],
                  use_tls=EMAIL['use_tls'],
                  usr=EMAIL['user'],
                  pwd=EMAIL['password']
                  )

    message = Message(From='*****@*****.**',
                      To=['*****@*****.**'],
                      Subject="message from {}".format(email)
                      )

    message.Body = """{} sent with email address {} sent you the following message:
                      {}
                   """.format(name, email, mess)
    try:
        mail.send(message)
    except Exception as e:
        log.error('Send mail error: {}'.format(str(e)))
コード例 #52
0
ファイル: views.py プロジェクト: CarlesLlobet/CoSA
 def put(self, request, id, format=None):
     task = w3af_requests.objects.get(id=id)
     print(task.id)
     e = request.data['state']
     task.state = e
     task.save()
     if e == "Finished":
         res = w3af_results.objects.get(id=id)
         res.finish_date = timezone.now()
         res.save()
         if task.mail:
             username = User.objects.get(id=task.user.id).username
             print("Username: "******"*****@*****.**",
                               To=[task.mail],
                               Subject=u'[AAPT] w3af Report')
             message.Body = u'Task ' + unicode(
                 task.name
             ) + u' has finished. To see the results:\n http://localhost:8080/w3af/task/' + unicode(
                 task.id) + u'/'
             sender = Mailer('localhost')
             sender.send(message)
     return Response(status=204)
コード例 #53
0
ファイル: sms.py プロジェクト: AnishGeorgeJlabs/vaadiSms
work = Queue.Queue()
i = 0
for x in data:
	if i is 0:
		pass
		i = i + 1
	else:
		work.put(x)
totalsent = work.qsize()
print totalsent


threads = []
for i in range(2):
	thread = threading.Thread(target=sendsend)
	thread.start()
	threads.append(thread)
print "Waiting"
for thread in threads:
	thread.join()
print "Done"
message = Message(From="Jarvis",
                  To=["*****@*****.**"],
                  Subject="Price Comparison")
message.Body = "Message sent to " + str(totalsent) + " customers"


sender = Mailer('smtp.gmail.com',port=587,use_tls=True)
sender.login("*****@*****.**","coldplay@123")
sender.send(message)
コード例 #54
0
ファイル: use_mailer.py プロジェクト: arunsingh/mailer
mailer = Mailer('smtp01.odn.ne.jp')

msg2 = Message(Body="ナイスボディー!", attachments=["picture.png"])
msg2.From = "*****@*****.**"
msg2.To = "*****@*****.**"
msg2.Subject = "日本語の添付ファイルメール"
msg2.charset = "utf-8"

mailer.send([msg1, msg2])

msg = Message()
msg.From = "*****@*****.**"
msg.To = "*****@*****.**"
msg.Subject = "テキストメール"
msg.Body = "これは日本語のキストメールでございます。"
msg.charset = "utf-8"
mailer.send(msg)

msg3 = Message(From="*****@*****.**",
                  To=["*****@*****.**", "*****@*****.**"],
                  charset="utf-8")
msg3.Subject = "HTML with Attachment"
msg3.Html = """Hello, <b>日本語</b>"""
msg3.attach("picture.png")
mailer.send(msg3)

# now try specifying the MIME type
msg4 = Message(From="*****@*****.**",
                  To=["*****@*****.**", "*****@*****.**"],
                  charset="utf-8")
コード例 #55
0
ファイル: upload_sievee.py プロジェクト: rizvir/upload-sievee
def send_email(ID):
	# Construct email, this is a biggie
	body = ""
	this_candidate_info = dict( g.conn.execute( select([g.candidates]).where(g.candidates.c.id == ID) ).fetchone().items() )

	# We have to figure out if this potential devil saw the questions before
	# This isn't fool proof of course, but can catch most attempts where they 
	# see the questions, close the window, research the answers, and try again.

	# Get a list of IDs that match the candidates email address, phone number
	# or (hesitated on this one) IP, and crucially those IDs in the DB that 
	# haven't completed the submission
	this_candidate_email = this_candidate_info['email']
	this_candidate_phone = this_candidate_info['phone']
	this_candidate_ip = this_candidate_info['ip']
	subject = "[Candidate] {0}".format(this_candidate_email)
	
	possible_candidates = g.conn.execute( select(['*']).where(
		and_(
			g.candidates.c.cv_uploaded == False,
			or_(
				g.candidates.c.email == this_candidate_email,
				g.candidates.c.phone == this_candidate_phone,
				g.candidates.c.ip    == this_candidate_ip,
			)
		)
	))
	
	attempts = []
	for candidate in possible_candidates:
		attempts.append( dict(candidate.items()) )

	attempts.append(this_candidate_info)
	# At this points, attempts[] has all the candidates attempts

	multiple_attempts = True if len(attempts) > 1 else False

	body += "Candidate info:\n"
	for attempt in attempts:
		if multiple_attempts:
			body += "--- Attempt ID {0} ---\n".format(attempt['id'])
		body += "- Name: {0}\n".format(attempt['name'])
		body += "- Email: {0}\n".format(attempt['email'])
		body += "- Phone: {0}\n".format(attempt['phone'])
		body += "- IP address: {0}\n".format(attempt['ip'])
		body += "- Browser: {0}\n".format(attempt['useragent'])
		body += "- Time: {0}\n".format(attempt['entry_date'])
		body += "\n"

	
	for code,title in [ ('basic_questions','Basic Questions'),  ('extra_questions','Extra Questions'), ('nontech_questions', 'Nontech Questions') ]:
		body += "_" * 60
		body += "\n"
		body += "{0}:\n\n".format(title)
		for attempt in attempts:
			if multiple_attempts:
				body += "--- Attempt ID {0} ---\n".format(attempt['id'])
			if attempt.get('{0}_start'.format(code), None)  and not attempt.get('{0}_end'.format(code), None):
				body += "The candidate saw the questions without attempting any on {0}\n\n".format(attempt['basic_questions_start'])
				continue
			# Now copy the .txt for this ID blindly
			body += get_answers(attempt['id'], '{0}.txt'.format(code))
			body += "\n"

	app.logger.debug(body)

	# Actually send the email:
	if not app.config['DEMO_MODE']:
		message = Message(From=app.config['MAIL_FROM'], To=app.config['MAIL_TO'])
		message.Subject = subject
		message.Body = body
		# Get attachments, all files in the repo ID
		path = "{0}/{1}/cv_upload".format(app.config['REPO_DIR'], this_candidate_info['id'])
		for filename in os.listdir(path):
			file_location = "{0}/{1}".format(path, filename)
			message.attach(file_location)
			app.logger.debug("Attaching {0}".format(file_location))
		sender = Mailer(app.config['MAIL_SERVER'])
		sender.send(message)
		return ""
	else:
		return body
コード例 #56
0
ファイル: bdsrotator.py プロジェクト: jelloir/bdsrotator
def relay_email(smtpserver, smtprecipient, smtpsender, smtpsubject, body):
    message = Message(From=smtpsender, To=smtprecipient.split(','), Subject=smtpsubject)
    message.Body = body
    sender = Mailer(smtpserver)
    sender.send(message)
コード例 #57
0
ファイル: module1.py プロジェクト: zodman/sendemails
        file_notsend.writerow(d)
        to =""
        continue
    if not "@" in d["Email"]:
        file_notsend.writerow(d)
        to=""
        continue
    else:
        to = d["Email"]

    m = Message(From= from_, To = to)
    m.attach("cote.gif","header")
    params = dict(
        razon_social=d["Descripcion"],
        numero_sap=d["ClaveSAP"],
        userid=d["UserName"],
        password=d["Password"]
    )
    str_html = str_html_back % params
    m.Subject = "NUEVA PAGINA WEB DE PROVEEDORES"

    m.Html = str_html
    m.Body = html2text.html2text(str_html).encode("utf8")
    try:
        sender.send(m)
        print "%s %s send"  % ( d["Email"], d["UserName"])
        file_send.writerow(d)
    except:
        print "%s %s not send "  % ( d["Email"], d["UserName"])
        file_fail.writerow(d)