Exemplo n.º 1
0
Arquivo: run.py Projeto: gmc-dev/hours
def send_email(date_from, date_to, email=config['email']['default_to'], worklogs=None):
    worklogs = worklogs or get_worklogs(date_from, date_to)

    # put data into weeks
    weeks = {}
    for date in worklogs:
        # add issue date
        for worklog in worklogs[date]:
            issue, description = get_jira_issue(worklog['task_name'])
            if not issue:
                worklog['issue'] = worklog['task_name']
                worklog['comment'] = ''
                continue

            worklog['issue'] = '<a href="%s" target="_blank">%s: %s</a>' % (issue.permalink(), str(issue), issue.fields.summary)
            worklog['comment'] = description

        week = '%i-%02i' % (date.year, date.isocalendar()[1])
        if week not in weeks:
            weeks[week] = {}
        weeks[week][date] = worklogs[date]

    html = build_email(weeks, config['email']['template'])

    connection = SESConnection(aws_access_key_id=config['email']['aws']['access_key_id'],
                               aws_secret_access_key=config['email']['aws']['secret_access_key'])

    subject = 'Hours report %s - %s' % (date_from.strftime('%m/%d'), date_to.strftime('%m/%d'))

    connection.send_email(config['email']['from'], subject, html, email, format='html')
Exemplo n.º 2
0
 def ses_notify(pricedict, stocks):
     print "notify", pricedict, stocks
     lines = []
     keys = pricedict.keys()
     keys.sort()
     if stocks:
         lines.append("big movers, %s" % ",".join(stocks))
     for k in keys:
         v = pricedict[k]
         lines.append("%s : %.2f" % (k,v))
     message = "\n".join(lines)
     print message
     import json
     with open("/home/yata/keys.json") as f:
         data = f.read()
         keys = json.loads(data)
     from boto.ses import SESConnection
     connection = SESConnection(
         aws_access_key_id=keys["AWS_ACCESS_KEY"],
         aws_secret_access_key=keys["AWS_SECRET_KEY"]
         )
     connection.send_email("*****@*****.**",
                           "stock update", message,
                           ["*****@*****.**", "*****@*****.**"],
                           )
Exemplo n.º 3
0
def ses_email(config, to_address, subject, body):
    connection = SESConnection(
        aws_access_key_id=config['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=config['AWS_SECRET_ACCESS_KEY_ID'])
    from_address = '"SolutionNet" <{0}>'.format(config['FROM_EMAIL_ADDRESS'])

    connection.send_email(from_address, str(subject), str(escape(body)),
                          str(to_address))
Exemplo n.º 4
0
def ses_email(config, to_address, subject, body):
    connection = SESConnection(
        aws_access_key_id=config['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=config['AWS_SECRET_ACCESS_KEY'],
        region=next(i for i in regions() if i.name == config['AWS_REGION']))
    from_address = '"SolutionNet" <{0}>'.format(config['FROM_EMAIL_ADDRESS'])

    connection.send_email(from_address, str(subject), str(body),
                          str(to_address))
Exemplo n.º 5
0
def ses_email(config, to_address, subject, body):
    connection = SESConnection(aws_access_key_id=config['AWS_ACCESS_KEY_ID'],
                               aws_secret_access_key=config['AWS_SECRET_ACCESS_KEY_ID'])
    from_address = '"SolutionNet" <{0}>'.format(config['FROM_EMAIL_ADDRESS'])

    connection.send_email(from_address,
                          str(subject),
                          str(escape(body)),
                          str(to_address))
Exemplo n.º 6
0
def send_mail_data(subject, body, format):
    connection = SESConnection(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    try:
        emails = Mail.objects.all().values_list('email', flat=True)
    except Mail.DoesNotExist:
        emails = []
    for i in range(0, len(emails), MAX_MAILS_PER_SEC):
        to_addresses = emails[i:(i + MAX_MAILS_PER_SEC)]
        connection.send_email(source=DEFAULT_EMAIL_SENDER, subject=subject, body=body,
                              to_addresses=DEFAULT_EMAIL_SENDER,
                              bcc_addresses=to_addresses,
                              format=format)
        time.sleep(1)
Exemplo n.º 7
0
class AWSSESSender:
    def __init__(self, aws_access_key, aws_secret_key):
        try:
            self.ses_conn = SESConnection(aws_access_key_id=aws_access_key,
                                          aws_secret_access_key=aws_secret_key)
        except:
            print "SES Connection was failed !!"
            exit()

    def send_email(self, sender, subject, body, recipient_list):
        if self.ses_conn != None:
            self.ses_conn.send_email(sender, subject, body, recipient_list)
        else:
            print "Connection object is null!!"

    def send_raw_email(self, sender, subject, body, recipient_list,
                       attachment_path):
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = sender

        to_list = ""

        for idx, data in enumerate(recipient_list):
            if idx < len(recipient_list) - 1:
                to_list += data + ","
            else:
                to_list += data

        msg['To'] = to_list
        msg.premable = 'Multipart Message.\n'

        # Assembling Mail body
        part = MIMEText(body)
        msg.attach(part)

        # Assembling Attachment
        part = MIMEApplication(open(attachment_path, 'rb').read())
        part.add_header('Content-Disposition',
                        'attachment',
                        filename=os.path.basename(attachment_path))
        msg.attach(part)

        # Send RAW email
        if self.ses_conn != None:
            self.ses_conn.send_raw_email(msg.as_string(),
                                         source=msg['From'],
                                         destinations=recipient_list)
        else:
            print "Connection object is null!!"
Exemplo n.º 8
0
def notify_user(user_notification):
    email = user_notification.user.email
    email_body = _body(user_notification)
    email_subject = _subject(user_notification)
    if settings.DEBUG:
        print("Sending email: {0} with subject: {1} to: {2}".format(
                email_string, email_subject, email))
    else:
        connection = SESConnection(
            aws_access_key_id=settings.AWS_ACCESS_KEY,
            aws_secret_access_key=settings.AWS_SECRET_KEY)
        connection.send_email(
            source="*****@*****.**",
            subject=email_subject,
            body=email_body,
            to_addresses=[email],
            format='html',
            cc_addresses=['*****@*****.**'])
Exemplo n.º 9
0
def _send_email(email, amount, confirm_code):
    if not settings.DEBUG:
        context = {
            'confirm_url': 'http://{0}{1}'.format(
                Site.objects.get_current().domain,
                reverse('main:confirm_pledge', args=[confirm_code])) }
        connection = SESConnection(
            aws_access_key_id=settings.AWS_ACCESS_KEY,
            aws_secret_access_key=settings.AWS_SECRET_KEY)
        connection.send_email(
            source="*****@*****.**",
            subject="Please confirm your pledge",
            body=render_to_string('pledge_email.html', context),
            to_addresses=[email],
            format='html',
            cc_addresses=['*****@*****.**'])
    else:
        print('Sent email to {0} about {1} with confirm code {2}'.format(
                email, amount, confirm_code))
Exemplo n.º 10
0
	def handle_noargs(self, **options):
		subject = 'hi krista'
		fromName = 'krista'
		fromAddress = '*****@*****.**'
		toAddressesStr = '*****@*****.**'
		textBody = 'hihihi'
		htmlBody = 'body yo yo yo'
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
    		msg = MIMEMultipart('alternative')
    		msg['Subject'] = subject
    		msg['From'] = "" + str(fromName) + " <" + fromAddress + ">"
    		msg['To'] = toAddressesStr
    
    		connection = SESConnection(aws_access_key_id=settings.AWS_ACCESS_KEY, 
				aws_secret_access_key=settings.AWS_SECRET_KEY)
    		connection.send_email(fromName + " <" + fromAddress + ">", 
			subject, body=htmlBody, 
			to_addresses=toAddressesStr, text_body=textBody, 
			format="html", return_path=fromAddress)
Exemplo n.º 11
0
def send(subject,body,toAddressesStr,fromName,fromAddress,replacements):
  connection = SESConnection(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)

  ###Send Welcome Email
  htmlBody = "%s%s%s" % (HEADER,body,END)

  textBody = "%s\n\n\n%s" % (strip_tags(body), "Use link below to unsubscribe from these reminders: \n{{unsubscribe}}")
  textBody = textBody.replace("&nbsp;","")
  textBody = textBody.replace("&rsquo;","'")
  textBody = textBody.replace("&lsquo;","'")
  textBody = textBody.replace("&rdquo;",'"')
  textBody = textBody.replace("&ldquo;",'"')

  for key, value in replacements.iteritems():
    textBody = textBody.replace(key,value)
    htmlBody = htmlBody.replace(key,value)
    subject = subject.replace(key,value)

  connection.send_email(fromName + " <" + fromAddress + ">", 
    subject, body=htmlBody, to_addresses=toAddressesStr, 
    text_body=textBody, format="html", 
    return_path=fromAddress)
Exemplo n.º 12
0
def send_email(fromaddr, toaddrs, subject, txtdata):
    from boto.ses import SESConnection
    connection = SESConnection(
        aws_access_key_id=keys["AWS_ACCESS_KEY"],
        aws_secret_access_key=keys["AWS_SECRET_KEY"])
    connection.send_email(fromaddr, subject, txtdata, toaddrs)
Exemplo n.º 13
0
class SESMessage(object):
    """
    Usage:

    msg = SESMessage('*****@*****.**', '*****@*****.**', 'The subject')
    msg.text = 'Text body'
    msg.html = 'HTML body'
    msg.send()

    """
    def __init__(self, source, to_addresses, subject, **kw):
        self.ses = SESConnection()

        self._source = source
        self._to_addresses = to_addresses
        self._cc_addresses = None
        self._bcc_addresses = None

        self.subject = subject
        self.text = None
        self.html = None
        self.attachments = []

    def send(self):
        if not self.ses:
            raise Exception, 'No connection found'

        if (self.text and not self.html and not self.attachments) or \
           (self.html and not self.text and not self.attachments):
            return self.ses.send_email(self._source,
                                       self.subject,
                                       self.text or self.html,
                                       self._to_addresses,
                                       self._cc_addresses,
                                       self._bcc_addresses,
                                       format='text' if self.text else 'html')
        else:
            if not self.attachments:
                message = MIMEMultipart('alternative')

                message['Subject'] = self.subject
                message['From'] = self._source
                if isinstance(self._to_addresses, (list, tuple)):
                    message['To'] = COMMASPACE.join(self._to_addresses)
                else:
                    message['To'] = self._to_addresses

                message.attach(MIMEText(self.text, 'plain'))
                message.attach(MIMEText(self.html, 'html'))
            else:
                raise NotImplementedError, 'SES does not currently allow ' + \
                                           'messages with attachments.'
#                message = MIMEMultipart()
#
#                message_alt = MIMEMultipart('alternative')
#
#                if self.text:
#                    message_alt.attach(MIMEText(self.text, 'plain'))
#                if self.html:
#                    message_alt.attach(MIMEText(self.html, 'html'))
#
#                message.attach(message_alt)
#
#                message['Subject'] = self.subject
#                message['From'] = self._source
#                if isinstance(self._to_addresses, (list, tuple)):
#                    message['To'] = COMMASPACE.join(self._to_addresses)
#                else:
#                    message['To'] = self._to_addresses
#                message.preamble = 'You will not see this in a MIME-aware mail reader.\n'

#                print 'message: ', message.as_string()

#                for attachment in self.attachments:
#                    # Guess the content type based on the file's extension.  Encoding
#                    # will be ignored, although we should check for simple things like
#                    # gzip'd or compressed files.
#                    ctype, encoding = mimetypes.guess_type(attachment)
#                    if ctype is None or encoding is not None:
#                        # No guess could be made, or the file is encoded (compressed), so
#                        # use a generic bag-of-bits type.
#                        ctype = 'application/octet-stream'
#                    maintype, subtype = ctype.split('/', 1)
#                    if maintype == 'text':
#                        fp = open(attachment)
#                        # Note: we should handle calculating the charset
#                        part = MIMEText(fp.read(), _subtype=subtype)
#                        fp.close()
#                    elif maintype == 'image':
#                        fp = open(attachment, 'rb')
#                        part = MIMEImage(fp.read(), _subtype=subtype)
#                        fp.close()
#                    elif maintype == 'audio':
#                        fp = open(attachment, 'rb')
#                        part = MIMEAudio(fp.read(), _subtype=subtype)
#                        fp.close()
#                    else:
#                        fp = open(attachment, 'rb')
#                        part = MIMEBase(maintype, subtype)
#                        part.set_payload(fp.read())
#                        fp.close()
#                        # Encode the payload using Base64
#                        encoders.encode_base64(part)
#                    # Set the filename parameter
#                    part.add_header('Content-Disposition', 'attachment', filename=attachment)
#                    message.attach(part)

            return self.ses.send_raw_email(self._source,
                                           message.as_string(),
                                           destinations=self._to_addresses)
class AmazonSES(object):
    EMPTY_EMAIL = "Email adress parameter is empty"
    TEMPLATE_NOT_FOUND = "Email template not found!"
    @classmethod
    def __init__(self,AWS_KEY,AWS_SECRET_KEY):
        self.connection = SESConnection(aws_access_key_id=AWS_KEY, aws_secret_access_key=AWS_SECRET_KEY)
        self.mimeType = "text"

    def replaceContent(self,content,param):
        for k,v in param.iteritems():
            content = content.replace(k,v)
        return content

    def sendEmail(self,email=None,subject=None,param=None,to_addresses=None,templatePath=None):
        print email
        print templatePath + " sss"
        if not self.connection:
            raise Exception, 'No connection found'

        if templatePath is None:
            raise Exception, "Please set to email template!"

        if email is None:
            result = {"status":"error","msg":self.EMPTY_EMAIL}
            result = self.jsonOutput(result)
            print result
            return result

        file = self.isReadFile(templatePath)
        if file is not False:
            if param is not None:
                message = self.replaceContent(file,param)
            else:
                message = file
        else:
            result = {"status":"error","msg":self.TEMPLATE_NOT_FOUND}
            result = self.jsonOutput(result)
            print result
            return result

        to_addresses = to_addresses

        print self.connection.send_email(email, subject, message,to_addresses ,None,None, self.mimeType, None, None)

    # template file is readable?
    # return string , bool
    def isReadFile(self,file):
        file = open(file).read()
        if file is not None:
            return file
        else:
            return False
    #email setting mimeType
    # default text
    def setMimeType(self,type):
        types = ["text","html"]
        if type in types:
            self.mimeType = type
        else:
            self.mimeType = "text";

    # print jsonOutput function
    def jsonOutput(self,dict):
        output = json.dumps(dict)
        return output
Exemplo n.º 15
0
def send_email(fromaddr, toaddrs, subject, txtdata):
    from boto.ses import SESConnection
    connection = SESConnection(aws_access_key_id=keys["AWS_ACCESS_KEY"],
                               aws_secret_access_key=keys["AWS_SECRET_KEY"])
    connection.send_email(fromaddr, subject, txtdata, toaddrs)