예제 #1
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)
예제 #2
0
    def message(self, name, log_file=None, error=None, **kwargs):
        """Create an email for the given stage based upon the log file.

        If no log file is provided or it is False then the email's body will
        not include the log lines to examine, and it will not be attached. If
        an error object is given this will be used to indicate the stage
        failed.

        :stage: Name of the stage that was run.
        :log_file: Filename for the log file
        :error: Exception object that occurred.
        :returns: A Mailer message to send.
        """

        status = 'Succeeded'
        if error:
            status = 'Failed'

        kwargs = {'stage': name, 'status': status}
        subject = self.config['email']['subject'].format(**kwargs)
        to_address = kwargs.get('send_to', None) or self.config['email']['to']
        msg = Message(From=self.config['email']['from'],
                      To=to_address,
                      Subject=subject,
                      Body=self.body(name, log_file, **kwargs))

        compressed_log = self.compressed_log(log_file)
        if compressed_log:
            msg.attach(compressed_log)

        return msg
예제 #3
0
    def message(self, name, log_file=None, error=None, **kwargs):
        """Create an email for the given stage based upon the log file.

        If no log file is provided or it is False then the email's body will
        not include the log lines to examine, and it will not be attached. If
        an error object is given this will be used to indicate the stage
        failed.

        :stage: Name of the stage that was run.
        :log_file: Filename for the log file
        :error: Exception object that occurred.
        :returns: A Mailer message to send.
        """

        status = 'Succeeded'
        if error:
            status = 'Failed'

        kwargs = {'stage': name, 'status': status}
        subject = self.config['email']['subject'].format(**kwargs)
        to_address = kwargs.get('send_to', None) or self.config['email']['to']
        msg = Message(
            From=self.config['email']['from'],
            To=to_address,
            Subject=subject,
            Body=self.body(name, log_file, **kwargs)
        )

        compressed_log = self.compressed_log(log_file)
        if compressed_log:
            msg.attach(compressed_log)

        return msg
예제 #4
0
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)
예제 #5
0
def sendMail(item, hwp):
    sender = Mailer('smtp.gmail.com', use_tls=True)
    for to in MAILER_TO:
        sender.login(MAILER_USERNAME, MAILER_PASSWORD)
        message = Message(From='*****@*****.**', To=to)
        message.Subject = "가정통신문 :%s" % item['title'].encode('utf-8')
        message.Html = ""
        if hwp:
            message.attach(hwp)
        sender.send(message)
예제 #6
0
def sendMail(item, hwp):
    sender = Mailer('smtp.gmail.com',use_tls=True)
    for to in MAILER_TO :
        sender.login(MAILER_USERNAME,MAILER_PASSWORD)
        message = Message(From='*****@*****.**', To=to)
        message.Subject = "가정통신문 :%s"%item['title'].encode('utf-8')
        message.Html = ""
        if hwp:
            message.attach(hwp)
        sender.send(message)
예제 #7
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)
예제 #8
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)
예제 #9
0
def SendMail(MailConfig, Content, filename=None):
    message = Message(From=MailConfig.SENDOR,
                      To=MailConfig.RECEIEVERS,
                      charset="utf-8")
    message.Subject = MailConfig.SUBJECT
    message.Html = Content
    if filename != None:
        message.attach(filename)
    server = smtplib.SMTP(MailConfig.SMTPSETTING)
    server.starttls()
    server.sendmail(MailConfig.SENDOR, MailConfig.RECEIEVERS.split(";"),
                    message.as_string())
    server.quit()
예제 #10
0
    def send_reply(self, message, toAddress):
        sender = Mailer(host=settings.host, port=settings.port, usr=settings.username, 
                    pwd=settings.password, use_tls=settings.tls)
        email  = Message(From=message['fromAddress'], To=toAddress, Subject=message['subject'], CC=message['ccAddress'])
        email.Html = message['body']

        messageUploads = '{}/{}/attachments/'.format(self.uploadsBasePath, message['_id'])

        for upload in os.listdir(messageUploads):
            email.attach('{}{}'.format(messageUploads, upload))

        print 'Sending {} to {}'.format(message['subject'], toAddress)
        
        sender.send(email)
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
예제 #12
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)
def email_kindle_guardian(from_email, kindle_email):
    now = datetime.datetime.now()
    file_name = "gdn-" + format(now.year, "02d") + "-" + format(now.month, "02d") + "-" + format(now.day, "02d") + ".mobi"
    url = "http://mythic-beasts.com/~mark/random/guardian-for-kindle/" + file_name
    # Download the file!
    req = Request(url)

    try:
        f = urlopen(req)
        print "Downloading " + url
        # Download the file to tmp
        with open("/tmp/" + file_name, "w+") as local_file:
            local_file.write(f.read())

        # Yey!, we've downloaded the file. Email it!
        message = Message(From=from_email, To=[kindle_email], Subject="Guardian " + file_name)
        message.attach("/tmp/" + file_name)
        sender = Mailer("localhost")
        sender.send(message)
        print "Yey! I've sent today's Guardian to " + kindle_email

    except HTTPError, e:
        print e.code, url
예제 #14
0
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")
msg4.Subject = "HTML with Attachment (MIME type specified)"
msg4.Html = """Hello, please have a look at this image."""
msg4.attach("picture.png", mimetype="image/png")
mailer.send(msg4)
예제 #15
0
파일: views.py 프로젝트: CarlesLlobet/CoSA
 def put(self, request, id, format=None):
     task = openvas_requests.objects.get(id=id)
     print(task.id)
     e = request.data['state']
     task.state = e
     task.save()
     if e == "Finished":
         result = openvas_results.objects.get(id=id)
         # Parsejar XML per treure High Medium i Low
         scanner = VulnscanManager("localhost", openvas_username,
                                   openvas_password)
         auxReport = scanner.get_report_xml(str(result.report))
         auxReportString = ElementTree.tostring(
             auxReport.find("report").find("report").find("results"),
             encoding='utf-8',
             method='xml')
         auxReportXML = ElementTree.fromstring(auxReportString)
         print(auxReportString)
         high = 0
         medium = 0
         low = 0
         log = 0
         for v in auxReportXML:
             print(str(v.find("threat").text))
             if v.find("threat").text == "High":
                 high += 1
             elif v.find("threat").text == "Medium":
                 medium += 1
             elif v.find("threat").text == "Low":
                 low += 1
             elif v.find("threat").text == "Log":
                 log += 1
         parsed = "High: " + str(high) + " / Medium: " + str(
             medium) + " / Low: " + str(low) + " / Log: " + str(log)
         print(parsed)
         # Inserting finish date and results
         result.finish_date = timezone.now()
         result.output = parsed
         result.save()
         if task.mail:
             report = scanner.get_report_pdf(str(result.report))
             fileName = "Report_" + task.name + "_" + datetime.strftime(
                 result.finish_date, "%Y%m%d%H%M") + ".pdf"
             reportXML = ElementTree.tostring(report.find("report"),
                                              encoding='utf-8',
                                              method='xml')
             fullReport = ElementTree.fromstring(reportXML)
             pdf = base64.b64decode(fullReport.find("in_use").tail)
             username = User.objects.get(id=task.user.id).username
             print("Username: "******"*****@*****.**",
                               To=[task.mail],
                               Subject=u'[AAPT] OpenVAS Report')
             message.Body = body.encode('utf-8')
             sender = Mailer('localhost')
             message.attach(filename=fileName,
                            content=pdf,
                            mimetype="application/pdf")
             sender.send(message)
     return Response(status=204)
예제 #16
0
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
예제 #17
0
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")
msg4.Subject = "HTML with Attachment (MIME type specified)"
msg4.Html = """Hello, please have a look at this image."""
msg4.attach("picture.png", mimetype="image/png")
mailer.send(msg4)
예제 #18
0
template = premailer.transform(template)

# Clean HTML
import lxml.html
from lxml.html.clean import Cleaner
cleaner = Cleaner()
cleaner.kill_tags = ['style', 'script']
page = cleaner.clean_html(lxml.html.fromstring(template))
assert not page.xpath('//style'), 'style'
assert not page.xpath('//script'), 'script'
template = lxml.html.tostring(page).decode('utf-8')

# Send mails
sender = Mailer('smtp.yandex.com.tr', port='465', use_ssl=True)
sender.login(config.user_mail, getpass('Password: '******'start')
for receiver_name, receiver_mail in receivers:
    try:
        message = Message(From=config.user_mail,
                          To=receiver_mail,
                          charset="utf-8")
        attachment_path = glob(
            os.path.join(config.attachments_path, receiver_name + '.*'))[0]
        message.Subject = config.subject
        message.Html = template.format(NAME=receiver_name)
        message.attach(attachment_path)
        sender.send(message)
    except Exception as ex:
        print(receiver_name, receiver_mail, 'Failed\n', ex)
print('Done')
예제 #19
0
csv_file = csv.DictReader(open("BD.csv"))

for d in csv_file:
    if int(d["Perfil"]) is not 2:
        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)