Example #1
0
def send_notification(request, client, acceptance):

    for emaildir in client.clientemail_set.all():
        with transaction.atomic():
            try:
                template = get_template('notifier/email_template.html')
                workPlanList = list(acceptance.work.workplan_set.order_by('finalDate'))
                contingencyPlanList = list(acceptance.work.contingencyplan_set.order_by('finalDate'))
                affectedList = list(acceptance.work.affected_set.filter(nit__iexact=client.nit))
                context = Context({'client': client, 'acceptance': acceptance, 'work': acceptance.work, 'wpList':workPlanList, 'cpList': contingencyPlanList, 'affectedList': affectedList})

                msg = template.render(context=context)

                f='static/image002.jpg'
                fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
                msg_img = MIMEImage(fp.read(), 'jpg')
                fp.close()
                msg_img.add_header('Content-ID', '<image002>')

                email = EmailMessage(subject='NOTIFICACION '+acceptance.work.number, to=[emaildir.email],body=msg, from_email='*****@*****.**' )
                email.content_subtype = "html"
                email.attach(msg_img)
                email.send()
                if acceptance.notifiedDate==None:
                    acceptance.notifiedDate = datetime.datetime.now()
                    acceptance.save()
                #messages.success(request, "mensaje enviado exitosamente a: "+emaildir.email)
            except Exception as e:
                messages.error(request, "Mensaje no enviado a: "+emaildir.email + "   " + e.message)

    return request
 def setUp(self):
     
     #set up the image for the message
     ePic = 'v:/workspace/HandlingEmail_Homework/src/python-logo.png'
     att = open(ePic, 'rb')
     img = MIMEImage(att.read())
     att.close()
     img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ePic))
     
     #set up the message body
     msgText = MIMEText("This is a test string", 'plain')
     
     #build the message
     msg = MIMEMultipart()
     msg['To'] = '*****@*****.**'
     msg['From'] = '*****@*****.**'
     msg['Subject'] = 'Test Email'
     msg.attach(msgText)
     msg.attach(img)
     self.Mmsg = msg
     
     #create a set for comparison
     self.attachmentSet = {msgText.as_string(), img.as_string()}
     
     #engages the function
     attachments = [ePic]
     mailObj = emailReturn('*****@*****.**', 'This is a test string', attachments)
     self.mailTest = mailObj
def send_image_email(path, title = u'Image Report', user = "******", pwd = p, to = ''):
  if to is '':
    to = user

  img = dict(title=title, path=path, cid=str(uuid.uuid4()))

  msg = MIMEMultipart('related')
  msg['Subject'] = Header(u'Report…', 'utf-8')
  msg['From'] = user
  msg['To'] = to
  msg_alternative = MIMEMultipart('alternative')
  msg.attach(msg_alternative)
  msg_text = MIMEText(u'[image: {title}]'.format(**img), 'plain', 'utf-8')
  msg_alternative.attach(msg_text)
  msg_html = MIMEText(u'<div dir="ltr">'
                     '<img src="cid:{cid}" alt="{alt}"><br></div>'
                     .format(alt=cgi.escape(img['title'], quote=True), **img), 'html', 'utf-8')
  msg_alternative.attach(msg_html)

  with open(img['path'], 'rb') as file:
      msg_image = MIMEImage(file.read(), name=os.path.basename(img['path']))
      msg.attach(msg_image)

  msg_image.add_header('Content-ID', '<{}>'.format(img['cid']))

  s = smtplib.SMTP(host='smtp.gmail.com',port=587)
  s.ehlo()
  s.starttls()
  s.ehlo()
  s.login(user,pwd)
  s.sendmail(user,to,msg.as_string())
  s.quit()
Example #4
0
File: utils.py Project: lslaz1/karl
def create_message(request, subject, html, from_email, mailify=True):
    message = MIMEMultipart('alternative')
    message['From'] = from_email
    message['Subject'] = subject

    if mailify:
        mailify_html(request, html, message)
    else:
        body_html = u'<html><body>%s</body></html>' % html
        bodyplain = html2text.html2text(body_html)
        message.attach(MIMEText(bodyplain.encode('UTF-8'), 'plain', 'UTF-8'))
        message.attach(MIMEText(body_html.encode('UTF-8'), 'html', 'UTF-8'))

    for k in request.params.keys():
        if k.startswith("attachment"):
            tmpattachment = request.params[k]
            if tmpattachment.filename:
                if tmpattachment.filename.endswith(('.png', '.tiff', '.gif', '.bmp', 'jpeg', '.tif', '.jpg')):
                    attachment = MIMEImage(tmpattachment.value)
                elif tmpattachment.filename.endswith(('.pdf', '.zip')):
                    attachment = MIMEApplication(tmpattachment.value)
                else:
                    attachment = MIMEText(tmpattachment.value)
                attachment.add_header('Content-Disposition',
                                      'attachment',
                                      filename=tmpattachment.filename)
                message.attach(attachment)

    return message
    def send_mail(self, correlations, time, script):
        """Simple convenience function which sends an email \
        from the configured sender to receivers.
        :param correlations: number representing the combined \
          number of threats to be reported.
        :type correlations: :mod:`int`
        :param time: the time it took for the calling program \
            to execute and finish successfully.
        :type time: :mod:`string`
        :param script: the script which was invoked such that a \
            detailed job description can be provided to correlation notifications.
        :type time: :mod:`string`
        """

        description = self.get_description(script)
        message = Template("""
        <br><img src="cid:image1" width="200"><br>
        <p>You are receiving this email because you are subscribed to <b>Assurant's Threat Intelligence notification service</b>.</p>
        <p><b>$corr threat correlation(s) have been identified</b> whilst running one of our threat correlation scripts.</p>
        <p>Identified correlations relate to: <b>$desc</b>.</p>
        <p>To view correlation(s) please visit the Kibana dashboard.</p>
        <p>Time taken to identify correlations was <b>$dur seconds</b>.</p>
        <p><i>To unsubscribe from this service please contact $sender</i>.</p>
        """)
        fullMessage = message.substitute(corr=correlations, dur=time, sender=sender, desc=description)
        # Create the root message and fill in the from, to, and subject headers
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = 'Assurant Threatelligence Update'
        msgRoot['From'] = sender
        msgRoot['To'] = receivers
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        
        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        msgText = MIMEText('This is the alternative plain text message.')
        msgAlternative.attach(msgText)
        
        # We reference the image in the IMG SRC attribute by the ID we give it below
        #msgRoot = MIMEText()
        msgText = MIMEText(fullMessage, 'html')
        msgAlternative.attach(msgText)

        # This example assumes the image is in the current directory
        fp = open('assurant-logo.png', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)

        smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(sender, '')
        smtpObj.sendmail(sender, receivers, msgRoot.as_string())
        smtpObj.quit()
Example #6
0
def mysendmail(mailist,subject,msg,filename=None):
    USERNAME,PASSWD,SMTP = mailconfig()
    MAIL_LIST = re.split(',|;',mailist)
    try:
        message = MIMEMultipart()
        message.attach(MIMEText(msg))
        message["Subject"] = subject
        message["From"] = USERNAME
        message["To"] = ";".join(MAIL_LIST)
        if filename != None and os.path.exists(filename):
            ctype,encoding = mimetypes.guess_type(filename)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"
            maintype,subtype = ctype.split("/",1)
            attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype)
            attachment.add_header("Content-Disposition", "attachment", filename = os.path.split(filename)[1])
            message.attach(attachment)
            
        s = smtplib.SMTP()
        s.connect(SMTP)
        s.login(USERNAME,PASSWD)
        s.sendmail(USERNAME,MAIL_LIST,message.as_string())
        s.quit()
        
        return True
    except Exception,errmsg:
        print "Send mail failed to : %s" % errmsg
        return False
Example #7
0
def sendMail():
	sender = '*****@*****.**'  
	receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']
	# receiver = ['*****@*****.**']
	smtpserver = 'mail.epcare.com.cn'  
	username = '******'  
	password = '******'  
	yestoday = date.today() - timedelta(hours=24);
	msgRoot = MIMEMultipart('related') 
	msgRoot['Subject'] = '每日域报告'
	msgRoot['From'] = sender
	msgRoot['To'] = ';'.join(receiver)
	msgRoot["Date"] = Utils.formatdate(localtime = 1)
	  
	#文本内容
	html = '''
	<html>
	    <head><head>
	    <body>
	        <p>Hi, all<br>
	            <br>
	            &nbsp;&nbsp;&nbsp;&nbsp;以上是昨天各个域的发送情况,详看附件!<br>
	            <br>
	            顺祝工作愉快!<br>
	            <br>
	            <img src="cid:image1">
	        </p>
	    </body>
	</html>
	'''
	msgText = MIMEText(html, 'html', 'utf-8')
	msgRoot.attach(msgText)
	fp = open('D:\\me.jpg', 'rb')
	msgImage = MIMEImage(fp.read())
	fp.close()
	msgImage.add_header('Content-ID', '<image1>')
	msgRoot.attach(msgImage)

	#构造附件  
	the_dir = 'C:\\Users\\zhang\\Desktop\\%s\\' % yestoday
	if os.path.exists(the_dir) :
	    os.chdir('%s' % (the_dir))
	else:
	    print 'no %s' % the_dir
	    sys.exit() 

	for dirfile in os.listdir(the_dir):
	    if os.path.isfile(dirfile):
	        csvfile = open(dirfile, 'rb')
	        att = MIMEText(csvfile.read(), 'base64', 'utf-8')  
	        csvfile.close()
	        att["Content-Type"] = 'application/octet-stream'  
	        att["Content-Disposition"] = 'attachment; filename="%s"'  % dirfile
	        msgRoot.attach(att)  
	          
	smtp = smtplib.SMTP()  
	smtp.connect(smtpserver)  
	smtp.login(username, password)  
	smtp.sendmail(sender, receiver, msgRoot.as_string())  
	smtp.quit()
def sendGmailwithpng(usr, pwd,recipients,subject,body,file):
	server = 'smtp.gmail.com'
	port = 587
	
	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['To'] = ",".join(recipients[0:])
	msg['From'] = usr
	
	path,filename = os.path.split(file)
	img = MIMEImage(open(file, 'rb').read(), _subtype="png")
	img.add_header('Content-Disposition', 'attachment', filename=filename)
	msg.attach(img)
	
	part = MIMEText('text', "plain")
	part.set_payload(body)
	msg.attach(part)
			   

	session = smtplib.SMTP(server, port)
	#~ session.set_debuglevel(True)
	session.ehlo()
	session.starttls()
	session.ehlo()
	session.login(usr,pwd)
	session.sendmail(usr, recipients,msg.as_string())
	session.quit()
Example #9
0
def emailTumblr(gmail_user_name, gmail_pass_word, random_word ):
  # now send the email to Tumblr
    # email set up
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()

    #Next, log in to the server
    #print "user: "******"pass: "******"rb").read(), _subtype="jpeg")
    img.add_header('Content-Disposition', 'attachment; filename="newImageChanged.jpg"')
    msg.attach(img)
    
    server.sendmail(me, tumblr_email, msg.as_string())
    server.quit()    
Example #10
0
def addimg(src,imgid):
    fp = open(src,'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID',imgid)

    return msgImage
def send_email(sender, recipient):
    """ Send email message """
    msg = MIMEMultipart()
    msg['Subject'] = 'Python Email Test'
    msg['To'] = recipient
    msg['From'] = sender
    subject = 'Python email Test'
    message = 'Images attached.'
    # attach image files
    files = os.listdir(os.getcwd())
    gifsearch = re.compile(".gif", re.IGNORECASE)
    files = filter(gifsearch.search, files)
    for filename in files:
        path = os.path.join(os.getcwd(), filename)
        if not os.path.isfile(path):
            continue
        img = MIMEImage(open(path, 'rb').read(), _subtype="gif")
        img.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(img)

    part = MIMEText('text', "plain")
    part.set_payload(message)
    msg.attach(part)

    # create smtp session
    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    session.ehlo()
    session.starttls()
    session.ehlo
    password = getpass.getpass(prompt="Enter you google's password: "******"Email sent."
    session.quit()
Example #12
0
def send_email():
    mail_username = EMAIL_USER_NAME
    mail_password = EMAIL_PASSWORD  
    from_addr = FROM_ADDRESS 
    to_addrs = TO_ADDRESS  
    #html_content
    send_html = get_html()
    # HOST & PORT  
    HOST = EMAIL_HOST  
    PORT = HOST_PORT
    # Create SMTP Object  
    smtp = smtplib.SMTP()  
    smtp.connect(HOST,PORT)  
    smtp.login(mail_username,mail_password)   
    msgRoot = MIMEMultipart('related')
    msg1 = MIMEText(send_html,'html','utf-8') 
    with open(IMAGE_PATH,'rb') as f:
        msg2 = MIMEImage(f.read())
        msg2['Content-Disposition'] = 'inline;filename="image.jpg"'
        msg2.add_header('Content-ID', '<image1>')    
    with open(TABLE_SAVE_PATH,'rb') as f:
        msg3 = MIMEText(f.read(),'base64','gb2312') 
        msg3["Content-Type"] = 'application'
        msg3["Content-Disposition"] = 'attachment;filename="爬虫库资源详情.xlsx"'
    msgRoot.attach(msg1) 
    msgRoot.attach(msg2)
    msgRoot.attach(msg3)
    msgRoot['From'] = from_addr
    msgRoot['To'] = ';'.join(to_addrs)
    msgRoot['Subject']= Header('爬虫库状态通知邮件(' + str(date.today()) + ')','utf-8') 
    smtp.sendmail(from_addr,to_addrs,msgRoot.as_string())  
    smtp.quit() 
Example #13
0
    def attachImage(self, content_id=None, jpeg=True, content_type=None, inline=False, force_filename=False, extension=None):
        if jpeg:
            real_filename = self.JPG_FILENAME
            file_suffix = 'jpg' if not extension else extension
        else:
            real_filename = self.PNG_FILENAME
            file_suffix = 'png' if not extension else extension

        with tempfile.NamedTemporaryFile(prefix="email2pdf_unittest_image", suffix="." + file_suffix) as temp_file:
            _, basic_file_name = os.path.split(temp_file.name)

        with open(real_filename, 'rb') as image_file:
            image = MIMEImage(image_file.read())
            if content_id:
                image.add_header('Content-ID', content_id)
            if content_type:
                self._replace_header(image, 'Content-Type', content_type)

            if inline:
                if force_filename:
                    self._replace_header(image, 'Content-Disposition', 'inline; filename="%s"' % basic_file_name)
                else:
                    self._replace_header(image, 'Content-Disposition', 'inline')
            else:
                self._replace_header(image, 'Content-Disposition', 'attachment; filename="%s"' % basic_file_name)
            self.msg.attach(image)

        if inline and not force_filename:
            return None
        else:
            return basic_file_name
Example #14
0
 def send_mail(self):
     # need to ensure address is minimally valid email
     sent_emails = ['', None]
     with open(os.path.join(
         BASE_DIR,
         'registration/static/registration/email_text/genericbanner.png'
     ), 'rb') as fp:
         image1 = MIMEImage(fp.read())
     image1.add_header('Content-ID', '<{}>'.format('image1'))
     for key in self._recipients:
         reg_id = key
         address = self._recipients[key]['email']
         salutation = self._recipients[key]['salutation']
         email_body = self._message
         if address not in sent_emails:
             if salutation not in ('', None):
                 email_body = 'Dear ' + salutation + ':<br/><br/>' + \
                     self._message
             if self._msg_type in ('docs', 'thanks'):
                 email_body = self._insert_passwords(email_body, key)
             email_body = '<img src="cid:image1" style="width:auto; max-width:90%;"/><br/><br/>' + email_body
             email_body = '<html><body>' + email_body + '</body></html>'
             email = EmailMessage(
                 subject = self._subject,
                 body = email_body,
                 to = [address]
             )
             email.content_subtype = 'html'
             email.mixed_subtype = 'related'
             email.attach(image1)
             email.send()
             sent_emails.append(address)
             time.sleep(SLEEP_TIME)
Example #15
0
def send_mail_with_pic(to_list,subject,pic=None):
	msg = MIMEMultipart()
	msg['To'] = ';'.join(to_list)
	msg['From'] = '*****@*****.**'
	msg['Subject'] = '%s' % subject

	txt = MIMEText("发送给你一些图片,瞧瞧吧,亲~~",'plain','utf8')
	msg.attach(txt)

	if pic == None:
		pic = ""
	else:
		for i in pic:
			if os.path.exists(i) != True:
				continue
			else:
				file1 = "%s" % i
				image = MIMEImage(open(file1,'rb').read())
				image.add_header('Content-ID','<image1>')
				msg.attach(image)

	server = smtplib.SMTP()
	server.connect(mail_host)
	server.starttls()
	server.login(mail_user,mail_pass)
	server.sendmail(msg['From'],msg['To'],msg.as_string())
	server.quit()
Example #16
0
 def sendmail(self,receiver,title,body):
     logfile = open('/usr/lib/zabbix/alertscripts/logs/alarm_mail.log','a')
     host = 'smtp.test.com'
     port = 25
     sender = '*****@*****.**'
     pwd = 'passwd'
     
     msg = MIMEMultipart('related')
     msg['subject'] = title
     msg['from'] = sender
     msg['To'] = ','.join(receiver)
     con_txt = MIMEText(body, 'html','utf-8')
     msg.attach(con_txt)
     img_path = '/usr/lib/zabbix/alertscripts/imgs/%s.png' %self.GetItemID(body)
     if os.path.exists(img_path):
         a = open(img_path,'r')
         img = a.read()
         a.close()
     else:
         a = open('/usr/lib/zabbix/alertscripts/imgs/404.jpg','r')
         img = a.read()
         a.close()
     con_img = MIMEImage(img)
     con_img.add_header('Content-ID','<img1>')
     msg.attach(con_img)
     try:  
         s = smtplib.SMTP(host, port)
         s.login(sender, pwd)
         s.sendmail(sender, receiver, msg.as_string())
         print 'The mail named %s to %s is sended successly.' % (title, receiver)
         log = '%s, OK,%s,%s\n' %(time.ctime(),title,receiver)
     except Exception,e:
         print "失败:"+str(e)
         log = '%s, Fail,%s,%s,%s\n' %(time.ctime(),title,receiver,str(e))
Example #17
0
File: alert.py Project: LS80/FFL
	def send(self, subject, html, smtp_server, images=[], zipfile=None):

		msg = MIMEMultipart()
		msg['From'] = '{0} <{1}>'.format(self.name, self.sender)
		msg['To'] = COMMASPACE.join(self.to)
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = subject
		if self.reply_to is not None:
			msg['Reply-To'] = self.reply_to
	
		msg.attach(MIMEText(html.encode('utf-8'), 'html', 'utf-8'))
		
		for i, image in enumerate(images):
			img = MIMEImage(image.read())
			img.add_header('Content-ID', '<image{0}>'.format(i+1))
			msg.attach(img)
		
		if zipfile:
			zip = MIMEBase('application', 'zip')
			zip.set_payload(zipfile.read())
			encoders.encode_base64(zip)
			zip.add_header('Content-Disposition', 'attachment; filename=%s' % basename(zipfile))
			msg.attach(zip)

		smtp = smtplib.SMTP(smtp_server)
		smtp.sendmail(self.sender, set(self.to+self.bcc), msg.as_string())
		smtp.close()
def emailReturn(eAddress, eBody, eAttach):
    msg = MIMEMultipart()
    msg['To'] = eAddress
    msgBody = MIMEText(eBody)
    msg.attach(msgBody)

    for attachment in eAttach:
        
        #test if it is an 
        mimeMainType = mimetypes.guess_type(attachment)[0].split('/')[0]
        mimeSubType = mimetypes.guess_type(attachment)[0].split('/')[1]
        if  mimeMainType == 'image':
            imgAttachment = open(attachment, 'rb')
            img = MIMEImage(imgAttachment.read())
            imgAttachment.close()
            img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
            msg.attach(img)
        elif mimeMainType == 'text':
            if mimeSubType == 'plain':
                plainText = MIMEText(attachment, 'plain')
                msg.attach(plainText)
            if mimeSubType == 'html':
                htmlText = MIMEText(attachment, 'html')
                msg.attach(htmlText)
    return msg
Example #19
0
def send_email_with_file(addressee, text, subject, file_list):
    """发送file email"""

    msg = MIMEMultipart()
    msg.attach(MIMEText(text, _charset='utf-8'))
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = '*****@*****.**'
    msg['To'] = addressee

    for file_name in file_list:
        ctype, encoding = mimetypes.guess_type(file_name)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        
        attachment = MIMEImage((lambda f: (f.read(), f.close())) \
                (open(file_name, 'rb'))[0], _subtype =subtype)
        attachment.add_header('Content-Disposition', 'attachment', filename=file_name)
        msg.attach(attachment)

    try:
        smtp = smtplib.SMTP()
        smtp.connect('smtp.ym.163.com', 25) 
        smtp.login(msg['From'], 'zhoujb.19890211') 
        smtp.sendmail(msg['From'], addressee, msg.as_string())
    except Exception,e:
        logger.exception('send_email: %s' % (str(e)))
Example #20
0
    def set_msg(self):
        msg = MIMEMultipart()
        msg["From"] = Mailer._format_addr((self.name + "<%s>" % self.email))
        msg["Subject"] = Header(self.sbj, "utf-8").encode()
        if self.mail_text:
            msg.attach(MIMEText(self.mail_text, "html", "utf-8"))
        else:
            raise Exception("| ERROR: Check your mail template")

        # Attach Logo
        with open(files["logo"], "rb") as l:
            logo = MIMEImage(l.read())
            logo.add_header("Content-ID", "<Logo>")
            logo.add_header("X-Attachment-Id", "Logo")
            msg.attach(logo)

        # Attach Pdf
        try:
            with open(files["attachment"], "rb") as ip:
                intro = MIMEApplication(ip.read())
                intro.add_header("Content-Disposition", "attachment", filename=files["attachment_name"])
                msg.attach(intro)
        except Exception as e:
            print("| ERROR: Wrong Attachment")
            print(e)

        return msg
Example #21
0
 def get_attachments(self):
     attachments = super().get_attachments()
     filename = finders.find('images/logo.png')
     f = open(filename, 'rb')
     opin_logo = MIMEImage(f.read())
     opin_logo.add_header('Content-ID', '<{}>'.format('opin_logo'))
     return attachments + [opin_logo]
Example #22
0
def new_message(address, body, args):
    # create new message
    msg = MIMEMultipart()
    msg["To"] = address
    p = MIMEText(body, "plain")
    msg.attach(p)
    
    if len(args) > 0:
        for a in args:
            # open the file
            f = open(a, "rb")

            # try to guess type and build appropriate object
            t = mimetypes.guess_type(a)
            if t[0].find("image") > -1:
                x = MIMEImage(f.read())
            elif t[0].find("application") > -1:
                x = MIMEApplication(f.read())
            
            f.close()
            
            # add header info
            x.add_header("Content-Disposition", "attachment", filename=os.path.basename(a))
            
            # attach to the message
            msg.attach(x)
    
    # return the message
    #print(msg.as_string())
    return msg
    
        
Example #23
0
def sendmail(sender, receivers, mail):
    message = MIMEMultipart()
    message['From'] = formataddr((Header(sender['nickname'], 'utf-8').encode(), sender['address']))
    message['To'] = ','.join(map(lambda x: formataddr((Header(x[0], 'utf-8').encode(), x[1])), receivers))
    message['Subject'] = Header(mail['subject'], 'utf-8').encode()

    if 'content' in mail:
        message.attach(MIMEText(mail['content'], 'plain', 'utf-8'))

    if 'content_html' in mail:
        message.attach(MIMEText(mail['content_html'], 'html', 'utf-8'))

    if 'attachments' in mail:
        for attachment in mail['attachments']:
            att = MIMEText(attachment[1], 'base64', 'utf-8')
            att["Content-Type"] = "application/octet-stream"
            att["Content-Disposition"] = 'attachment; filename="{}"'.format(attachment[0])
            message.attach(att)

    if 'images' in mail:
        for image in mail['images']:
            img = MIMEImage(image['data'])
            img.add_header('Content-ID', '<{}>'.format(image['Content-ID']))
            message.attach(img)

    server = smtplib.SMTP_SSL(sender['smtp_server'], sender['smtp_port'])
    server.login(sender['address'], sender['password'])
    server.sendmail(sender['address'], list(zip(*receivers))[1], message.as_string())
    server.quit()
Example #24
0
def create_and_send_mail_messages(messages):
    if not settings.EMAIL_HOST:
        return

    sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
    sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
    sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))

    try:
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT))
        """
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
                          local_hostname=DNS_NAME.get_fqdn())
        """
        
        if (bool(settings.EMAIL_USE_TLS)):
            connection.ehlo()
            connection.starttls()
            connection.ehlo()

        if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
            connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))

        if sender is None:
            sender = str(settings.DEFAULT_FROM_EMAIL)

        for recipient, subject, html, text, media in messages:
            msgRoot = MIMEMultipart('related')

            msgRoot['Subject'] = Header(subject, 'utf-8')
            msgRoot['From'] = sender

            to = Header(recipient.username, 'utf-8')
            to.append('<%s>' % recipient.email)
            msgRoot['To'] = to

            #msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')

            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)

            msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
            msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))

            for alias, location in media.items():
                fp = open(location, 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', '<'+alias+'>')
                msgRoot.attach(msgImage)

            try:
                connection.sendmail(sender, [recipient.email], msgRoot.as_string())
            except Exception, e:
                logging.error("Couldn't send mail using the sendmail method: %s" % e)

        try:
            connection.quit()
        except socket.sslerror:
            connection.close()
Example #25
0
def generate_message(folder, mail_subject, mail_from, mail_to):
    message = MIMEMultipart()
    message['Subject'] = mail_subject
    message['From'] = mail_from
    message['To'] = mail_to

    related = MIMEMultipart('related')
    message.attach(related)

    content = open(os.path.join(folder, "generated.html")).read()
    images = []
    print(os.listdir(folder))
    for file in os.listdir(folder):
        _, extension = os.path.splitext(file)
        print(file, _, extension, mimetypes.types_map.get(extension, "unknown").startswith("image/"))
        if mimetypes.types_map.get(extension, "unknown").startswith("image/"):
            with open(os.path.join(folder, file), 'rb') as fp:
                img = MIMEImage(fp.read(), name=file)
                img.add_header('Content-ID', "<" + file + "@mailer>")
                img.add_header('Content-Disposition', 'inline', filename=file)
                content = content.replace(file, "cid:" + file + "@mailer")
                images.append(img)

    related.attach(MIMEText(content, 'html', "utf-8"))
    for image in images:
        related.attach(image)

    return message
Example #26
0
def inflate(config, template, datas):
    sender = config['sender']
    subject = template['subject']
    body_template = Template(template['body'])

    attachments = []
    for cid in template['attachment'].keys():
        info = template['attachment'][cid]
        with open(info['path'], 'rb') as f:
            image = MIMEImage(f.read())
            image.add_header('Content-ID', '<{0}>'.format(cid))
            attachments.append(image)
    
    for data in datas:
        receiver = data['email']
        root = MIMEMultipart('related')
        root['Subject'] = subject
        root['From'] = sender
        root['To'] = receiver

        try:
            body = body_template.render(**data)
        except:
            raise Exception("Check template's variables and csv header")
        
        text = MIMEText(body, 'html', 'utf-8')

        root.attach(text)
        for attach in attachments:
            root.attach(attach)

        yield dict(
            sender = sender,
            receiver = receiver,
            message = root)
Example #27
0
def main():
    msg = MIMEMultipart()
    msg['Subject'] = 'Python (-++-) Test'
    msg['To'] = recipient
    msg['From'] = sender

    files = os.listdir(directory)
    pngsearch = re.compile(".png", re.IGNORECASE)
    files = filter(pngsearch.search, files)
    for filename in files:
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue

        img = MIMEImage(open(path, 'rb').read(), _subtype="png")
        img.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(img)

    part = MIMEText('text', "plain")
    part.set_payload(message)
    msg.attach(part)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, password)

    session.sendmail(sender, recipient, msg.as_string())
    session.quit()
Example #28
0
 def __send(to_list, sub, content, filenames = None):
     try:
         message = MIMEMultipart()
         message.attach(MIMEText(content, _subtype = 'html', _charset = 'UTF-8'))
         message["Subject"] = sub
         message["From"] = EmailUtil.me
         message["To"] = ";".join(to_list)
         if filenames is not None :
             for filename in filenames :
                 if os.path.exists(filename):
                     ctype, encoding = mimetypes.guess_type(filename)
                     if ctype is None or encoding is not None:
                         ctype = "application/octet-stream"
                     subtype = ctype.split("/", 1)
                     attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype)
                     attachment.add_header("Content-Disposition", "attachment", filename = re.findall('\/(\w+\.\w+)$', filename)[0])
                     message.attach(attachment)
         server = smtplib.SMTP()
         server.connect(EmailUtil.mail_host)
         server.login(EmailUtil.mail_user, EmailUtil.mail_pass)
         server.sendmail(EmailUtil.me, to_list, message.as_string())
         server.close()
         return True
     except Exception, e:
         print 'EmailUtil.__send error:', str(e)
def avatar_updated_handler(sender, instance, **kwargs):

    try:
        original_mentor = Mentor.objects.get(id=instance.id)
    except ObjectDoesNotExist:
        return

    if not instance.avatar:
        return

    if original_mentor.avatar != instance.avatar:
        instance.avatar_approved = False

        img = MIMEImage(instance.avatar.read())
        img.add_header('Content-Id', 'avatar')
        img.add_header("Content-Disposition", "inline", filename="avatar")

        email(
            subject=f"{instance.user.first_name} {instance.user.last_name} | Mentor Avatar Changed",
            template_name='avatar-changed-mentor',
            merge_global_data={
                'first_name': instance.user.first_name,
                'last_name': instance.user.last_name,
                'image': 'avatar',
                'approve_url': f"{settings.SITE_URL}{instance.get_approve_avatar_url()}",
                'reject_url': f"{settings.SITE_URL}{instance.get_reject_avatar_url()}",
            },
            recipients=[settings.CONTACT_EMAIL],
            preheader='Mentor Avatar Changed',
            attachments=[img],
            mixed_subtype='related',
        )
Example #30
0
def _build_multipart_msg(message, images):
    """Build Multipart message with in-line images."""
    _LOGGER.debug('Building multipart email with embedded attachment(s)')
    msg = MIMEMultipart('related')
    msg_alt = MIMEMultipart('alternative')
    msg.attach(msg_alt)
    body_txt = MIMEText(message)
    msg_alt.attach(body_txt)
    body_text = ['<p>{}</p><br>'.format(message)]

    for atch_num, atch_name in enumerate(images):
        cid = 'image{}'.format(atch_num)
        body_text.append('<img src="cid:{}"><br>'.format(cid))
        try:
            with open(atch_name, 'rb') as attachment_file:
                attachment = MIMEImage(attachment_file.read())
                msg.attach(attachment)
                attachment.add_header('Content-ID', '<{}>'.format(cid))
        except FileNotFoundError:
            _LOGGER.warning('Attachment %s not found. Skipping',
                            atch_name)

    body_html = MIMEText(''.join(body_text), 'html')
    msg_alt.attach(body_html)
    return msg
Example #31
0
def addimg(src, imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage
Example #32
0
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)

# This example assumes the image is in the current directory
fp = open('nationAllBal.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

# Send the email (this example assumes SMTP authentication is required)
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.ehlo()
smtp.starttls()
smtp.login(strFrom, config["get"]["PASSWORD"])
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
Example #33
0
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import pyautogui
import smtplib

screen = pyautogui.screenshot()
screen.save('screen.jpg')

credenfile = open("credentials.txt", 'r')
credentials = credenfile.readlines()
credenfile.close()

msg = MIMEMultipart()
msg['From'] = credentials[0]
password = credentials[1]
msg['To'] = credentials[2]
msg['subject'] = "screen"
fichier = open('screen.jpg', 'rb')
image = MIMEImage(fichier.read())
fichier.close()
msg.attach(image)

server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()


Example #34
0
    def send_email_by_qq(self,to):
        pass
        sender_mail='*****@*****.**' # 发送方的邮箱地址
        sender_pass = '******' # 邮箱提供的授权码,可在第三方登录。
        sftp_obj =smtplib.SMTP('smtp.qq.com', 25)
        sftp_obj.login(sender_mail, sender_pass)
        #三个参数分别是:发件人邮箱账号,收件人邮箱账号,发送的邮件体
        
        # 设置总的邮件体对象,对象类型为mixed
        msg_root = MIMEMultipart('mixed')
        # 邮件添加的头尾信息等
        msg_root['From'] = '[email protected]<*****@*****.**>'
        #msg_root['To'] = to
        msg_root['To'] = ",".join(to)
        subject = 'Please check stock report'
        msg_root['subject'] = Header(subject, 'utf-8')

        # 构造文本内容
        text_info = 'Stock report of %s'%self.reportFile
        text_sub = MIMEText(text_info, 'plain', 'utf-8')
        msg_root.attach(text_sub)

        # 构造超文本
        # url = "https://blog.csdn.net/chinesepython"
        # html_info = """
        # <p>点击以下链接,你会去向一个更大的世界</p>
        # <p><a href="%s">click me</a></p>
        # <p>i am very galsses for you</p>
        # """% url
        # html_sub = MIMEText(html_info, 'html', 'utf-8')
        # # 如果不加下边这行代码的话,上边的文本是不会正常显示的,会把超文本的内容当做文本显示
        # html_sub["Content-Disposition"] = 'attachment; filename="csdn.html"'   
        # # 把构造的内容写到邮件体中
        # msg_root.attach(html_sub)

        # 构造图片
        image_file = open(self.reportFile, 'rb').read()
        image = MIMEImage(image_file)
        image.add_header('Content-ID', '<image1>')
        # 如果不加下边这行代码的话,会在收件方方面显示乱码的bin文件,下载之后也不能正常打开
        image["Content-Disposition"] = 'attachment; filename="red_people.jpg"'
        msg_root.attach(image)

        # 构造附件
        # txt_file = open(r'C:\StockReport\report\test.txt', 'rb').read()
        # txt = MIMEText(txt_file, 'base64', 'utf-8')
        # txt["Content-Type"] = 'application/octet-stream'
        # #以下代码可以重命名附件为hello_world.txt  
        # txt.add_header('Content-Disposition', 'attachment', filename='test.txt')
        # msg_root.attach(txt)

        try:
            sftp_obj =smtplib.SMTP('smtp.qq.com', 25)
            sftp_obj.login(sender_mail, sender_pass)
            sftp_obj.sendmail(sender_mail, to, msg_root.as_string())
            sftp_obj.quit()
            print('sendemail successful!')

        except Exception as e:
            print('sendemail failed next is the reason')
            print(e)
Example #35
0
    def save(self, **vars):
        data = {}

        MealType = http.request.env['evaluacion.model']
        '''save = MealType.create({ 
				'tiempoLlegada' : '',
				'atencionTecnico' : '',
				'arregloTecnico' : '',
				'cuidadoTecnico' : '',
				'refacciones' : '',
				'whyRefacciones' : '',
				'herramientas' : '',
				'whyherramientas' : '',
				'volver' : '',
				'whyvolver' : '',
				'observaciones' : '', 
			})

		print (save)'''

        reference = vars['data']['pedido'].split(" ")

        http.request.env.cr.execute(
            "SELECT id, partner_id, user_id FROM pos_order WHERE pos_reference LIKE '%"
            + reference[len(reference) - 1] + "'")

        result = http.request.cr.fetchall()

        save = MealType.create({
            'cliente_id': result[0][1],
            'socio_id': result[0][2],
            'puntoVenta_id': result[0][0]
        })

        last_id = save and max(save)

        http.request.env.cr.execute(
            "SELECT email FROM res_partner WHERE id = " + str(result[0][1]))

        result = http.request.cr.fetchall()

        import os
        import smtplib
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText
        from email.mime.image import MIMEImage

        path = os.path.join(os.path.dirname(os.path.abspath(__file__)))

        fromaddr = "MrPlumber <*****@*****.**>"
        toaddr = result[0][0]
        msg = MIMEMultipart('alternative')

        msg['From'] = fromaddr
        msg['Subject'] = "MrPlumber"
        msg['To'] = toaddr

        http.request.env.cr.execute("SELECT MAX(id) FROM evaluacion_model")

        result = http.request.cr.fetchall()

        body = """\
				<html>
				  <head></head>
				  <body>
				    <a style="text-decoration: none;" href='""" + http.request.env[
            'ir.config_parameter'].sudo(
            ).get_param('web.base.url') + """/evaluacion/""" + str(
                result[0][0]
            ) + """'><center><div class="btn" style="background-color: #e66231;color: white;font-size: 3em;font-weight: bold;    -webkit-box-shadow: 0 16px 24px 2px rgba(0,0,0,0.14), 0 6px 30px 5px rgba(0,0,0,0.12), 0 8px 10px -7px rgba(0,0,0,0.2);box-shadow: 0 16px 24px 2px rgba(0,0,0,0.14), 0 6px 30px 5px rgba(0,0,0,0.12), 0 8px 10px -7px rgba(0,0,0,0.2)">Contestar encuesta</div></center></a>
				  </body>
				</html>
				"""

        import base64
        aaa = bytes(vars['data']['canvas'].split(',')[1], 'utf-8')
        with open(path + "/tickets/" + reference[len(reference) - 1] + ".png",
                  "wb") as fh:
            fh.write(base64.decodebytes(aaa))

        fp = open(path + "/tickets/" + reference[len(reference) - 1] + ".png",
                  'rb')
        img = MIMEImage(fp.read())
        fp.close()
        img.add_header(
            'Content-Disposition',
            'attachment; filename=' + reference[len(reference) - 1] + '.png')
        msg.attach(img)

        msg.attach(MIMEText(body, 'html'))
        text = msg.as_string()

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login("*****@*****.**", "mrplumber12345")
        server.sendmail(fromaddr, toaddr, text)
        server.sendmail(fromaddr, "*****@*****.**", text)
        server.sendmail(fromaddr, "*****@*****.**", text)
        server.sendmail(fromaddr, "*****@*****.**", text)
        server.sendmail(fromaddr, "*****@*****.**", text)
        '''http.request.env.cr.execute("UPDATE evaluacion_model SET status='False' WHERE id="+id)

		http.request.env.cr.execute("SELECT id, cliente_id, socio_id, encuesta_id, status FROM evaluacion_model")

		print (http.request.cr.fetchall())'''

        return {
            'message': 'Formulario guardado',
            'status': '200',
        }
Example #36
0
def compose(sender, reply_to, recipients, subject, body, attachments, style, logo_url):
    """compose an email message"""

    email = MIMEMultipart()
    email['Subject'] = subject
    email['From'] = formataddr(sender)
    email['To'] = display_email_address(recipients)
    if sender != reply_to:
        email['Reply-To'] = formataddr(reply_to)
    email.preamble = (
        'This message is in MIME format. '
        'You will not see this in a MIME-aware mail reader.\n'
    )
    email.epilogue = ''  # To guarantee the message ends with a newline

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they
    # want to display.
    msg_alternative = MIMEMultipart('alternative')
    email.attach(msg_alternative)

    # if isinstance(body, str):
    #     body = body.encode('utf8')
    #
    # simple encoding test, we will leave as ascii if possible (readable)
    _char = 'us-ascii'
    try:
        body.encode('ascii')
    except UnicodeDecodeError:
        _char = 'utf8'
    except AttributeError:
        _char = 'utf8'

    # attach a plain text version of the html email
    if style == 'html':
        msg_alternative.attach(
            MIMEText(get_plain_from_html(body), 'plain', _char)
        )
        body = format_as_html(body, logo_url)
    body = MIMEText(body.encode('utf8'), style, _char)
    msg_alternative.attach(body)

    for attachment in attachments or []:
        # 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 = guess_type(attachment.filename)
        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' or (
                ctype is not None and
                attachment.filename[-4:].lower() == '.ini'
            ):
            # Note: we should handle calculating the charset
            msg = MIMEText(attachment.read(), _subtype=subtype)
        elif maintype == 'image':
            msg = MIMEImage(attachment.read(), _subtype=subtype)
        elif maintype == 'audio':
            msg = MIMEAudio(attachment.read(), _subtype=subtype)
        else:
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(attachment.read())
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header(
            'Content-Disposition',
            'attachment',
            filename=attachment.filename
        )
        email.attach(msg)

    return email.as_string()
Example #37
0
msg.preamble = "Resultaten netwerkscan: " + str(d)

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP('smtp.gmail.com', 587)
Example #38
0
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
# mm["To"] = "receiver_1_name<*****@*****.**>,receiver_2_name<*****@*****.**>"
mm["To"] = "hgb<*****@*****.**>"
# 设置邮件主题
mm["Subject"] = Header(subject_content, 'utf-8')
# 邮件正文内容
body_content = """测试邮件"""
# 构造文本,参数 1:正文内容;2:文本格式;3:编码方式
message_text = MIMEText(body_content, "plain", "utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)

# 二进制读取图片
image_data = open('a.jpg', 'rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)

# 构造附件
atta = MIMEText(open('a.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息 Disposition:排列 attachment:附件
atta["Content-Disposition"] = 'attachment; filename="a.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)

# 发送邮件
# 创建SMTP对象
stp = smtplib.SMTP()
Example #39
0
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./FYP_part1.py"], stdout=output)

with open('output.txt', 'r') as myfile:
    data = myfile.read().replace('\n', '')

str = "score"
j = data.find(str, 0, len(data))
if j >= 0:
    i = data.index(str)
    score = data[i + 8:i + 12]
if j == -1 or (j >= 0 and float(score) < 0.75):
    attachment = '/home/pi/test1.jpg'
    fp = open(attachment, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg = MIMEMultipart()
    msg.attach(img)
    content = 'Hi python'
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    mail.ehlo()
    mail.starttls()
    mail.login('*****@*****.**', 'password')
    mail.sendmail('*****@*****.**', '*****@*****.**',
                  msg.as_string())
    mail.close()

else:
    EditZipFile()
Example #40
0
def sendEmail(path, receivers):
    # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "******"  # 用户名
    mail_pass = "******"  # 口令

    sender = '*****@*****.**'
    if receivers is None:
        receivers = '<*****@*****.**>;<*****@*****.**>'  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    msgRoot = MIMEMultipart()
    msgRoot['From'] = Header("自动化测试系统", 'utf-8')
    msgRoot['To'] = receivers
    # 主题
    now = time.strftime("%Y-%m-%d %H:%M:%S")
    subject = now + '自动化测试报告'
    content = now + '<html><h1>钻石会自动化测试报告</h1><h2>' \
                    '</h2><h3>点击下图跳转至报告详情</h3><h4>(或下载附件html和json,再通过本地浏览器打开)</h4></html>'
    msgRoot['Subject'] = Header(subject, 'utf-8')

    # html
    # content  = '<a href="http://172.22.12.194:1024/test_report.html">点击查看报告详情</a>'
    # 启动本地服务
    # os.system(r"cd C:\Users\Administrator\PycharmProjects\test_menber\report &python -m http.server 1024")
    msgText = MIMEText(content, 'html', 'utf-8')
    msgRoot.attach(msgText)
    # 显示图片
    content = '<a href="http://172.22.12.194:1024/test_report.html"><img src="cid:0" alt="test_report" /></a><br>'
    msgText = MIMEText(content, 'html', 'utf-8')
    msgRoot.attach(msgText)

    # 构造附件
    att1_path = path + '/report/test_report.html'
    att1 = MIMEText(open(att1_path, 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="test_report.html"'
    msgRoot.attach(att1)

    json_path = path + '/report/test_report.json'
    att2 = MIMEText(open(json_path, 'rb').read(), 'base64', 'utf-8')
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = 'attachment; filename="test_report.json"'
    msgRoot.attach(att2)

    # 附件图片
    pic_path = path + "/report/picture/test_report.png"
    img = MIMEImage(open(pic_path, 'rb').read(), _subtype='octet-stream')
    img.add_header('Content-Disposition', 'attachment', filename=pic_path)
    img.add_header('Content-ID', '<0>')  # 增加编号,HTML中通过引用 src="cid:0",可以引用附件
    img.add_header('X-Attachment-Id', '0')
    msgRoot.attach(img)

    try:
        smtp = smtplib.SMTP_SSL(mail_host)
        smtp.connect(mail_host, port=465)
        smtp.login(mail_user, mail_pass)
        smtp.sendmail(sender, receivers, msgRoot.as_string())
        print(subject + '>>>>>>邮件发送成功')
        smtp.quit()
    except smtplib.SMTPException as e:
        print('error:', e)  # 打印错误
Example #41
0
        extra = MIMEBase("application", "octet-stream")
        extra.set_payload(b"test content")
        encoders.encode_base64(extra)
        extra.add_header("Content-Disposition", "attachment", filename="report.pdf")
        instance.attach(extra)
        instance["X-Accept-Language"] = "en-us, en"
    for key, value in kwargs.items():
        instance[key] = value
    return instance


MIME_MESSAGE = get_mime_message("Text", **DEFAULT_HEADERS)
MIME_ALTERNATIVE = get_mime_message("Text", "HTML content", **DEFAULT_HEADERS)
ENCODED_CONTENT = "dGVzdCBjb250ZW50\n"

IMAGE = MIMEImage(b"test content", "png", name="image1.png")
IMAGE.add_header("Content-ID", "<*****@*****.**>")
IMAGE_NO_BRACKETS = MIMEImage(b"test content", "png", name="image2.png")
IMAGE_NO_BRACKETS.add_header("Content-ID", "*****@*****.**")
INLINE_IMAGE = MIMEImage(b"test content", "png", name="image3.png")
INLINE_IMAGE.add_header("Content-ID", "<*****@*****.**>")
INLINE_IMAGE.add_header("Content-Disposition", "inline", filename="image3.png")


class TestSimpleSend:
    @pytest.fixture
    def minimal_data(self):
        return {
            "From": "*****@*****.**",
            "To": "*****@*****.**",
            "Subject": "Postmark test",
Example #42
0
def send_email(video_id):
    logger.info('Trying to send email for video {0!r}'.format(video_id))

    msg = MIMEMultipart()
    msg['Subject'] = 'Motion detected'
    msg['To'] = settings.MAIL_RECIPIENT
    msg['From'] = settings.MAIL_SERVER_LOGIN

    files = os.listdir(settings.MOTION_DIRECTORY)
    cam_video_search = re.compile(r'''(?P<file_index>\d+)-\d+\.avi''')

    cam_video_match = cam_video_search.match(video_id)
    if cam_video_match is None:
        logger.warn('Could not find video {0!r}'.format(video_id))
        return

    index = cam_video_match.group('file_index')

    cam_image_search = re.compile(r'''{0}-\d+-\d+\.jpg'''.format(index))

    files = filter(cam_image_search.search,
                   files)[:settings.MAIL_PICTURE_NUMBER]
    logger.info('Attaching pictures')
    for filename in files:
        logger.info('Attaching picture {0}'.format(filename))

        path = os.path.join(settings.MOTION_DIRECTORY, filename)
        if not os.path.isfile(path):
            continue

        img = MIMEImage(open(path, 'rb').read(), _subtype="jpg")
        img.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(img)

    if settings.MAIL_SEND_VIDEO:
        logger.info('Attaching video')
        part = MIMEBase('application', "octet-stream")
        video_path = os.path.join(settings.MOTION_DIRECTORY, video_id)
        fo = open(video_path, "rb")
        part.set_payload(fo.read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="{0}"'\
            .format(os.path.basename(video_id)))
        msg.attach(part)

    logger.info('Attaching text')
    part = MIMEText('text', "plain", 'utf-8')
    part.set_payload('Motion has been detected')
    msg.attach(part)

    logger.info('Opening session on {0}:{1}'.format(settings.MAIL_SERVER_HOST,
                                                    settings.MAIL_SERVER_PORT))
    session = smtplib.SMTP(settings.MAIL_SERVER_HOST,
                           settings.MAIL_SERVER_PORT)

    logger.info('Starting TLS')
    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(settings.MAIL_SERVER_LOGIN, settings.MAIL_SERVER_PASSWORD)

    logger.info('Sending email for video {0!r}....'.format(video_id))

    session.sendmail(settings.MAIL_SERVER_LOGIN, settings.MAIL_RECIPIENT,
                     msg.as_string())
    session.quit()

    logger.info('Done: send email for video {0!r}'.format(video_id))
def automateThought(urlOfQuoteOftheDay):
    print("Intializing thought of the day")

    #All the Details at first fromAddress(sender email id), to Address(reciever's email id) and subject of the mail
    fromAddress = "*****@*****.**"
    print("Preparing Addresses to send!!")
    dLs = [
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**", "*****@*****.**", "*****@*****.**",
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**"
    ]
    #toAddress="*****@*****.**"
    subject = "It's test mail please ignore this"

    #Downloading image from the web using our own custom module "Downloading_image_from_web"
    print("Trying To Fetch Image from the web!!")
    Downloading_image_from_web.downloadImageFromWeb(urlOfQuoteOftheDay)
    print("Image Fecthed Successfully")

    #Creating a mime multipart message
    server = smtplib.SMTP("smtp.gmail.com", "587")
    print("Contacting Server")
    server.starttls()
    server.login("*****@*****.**", "rohitwalecha")
    print("Loging In")
    for toAddress in dLs:
        '''
    
        msg = MIMEMultipart('alternative')
        msg["To"] = toAddress
        msg["From"] = fromAddress
        msg["Subject"] = subject

    
        #Text to be sent in mail
        #body="Hi This is an automated tought of the day using web scraping!! "

        #Downloading image from the web using our own custom module "Downloading_image_from_web"
        print("Trying To Fetch Image from the web!!")
        Downloading_image_from_web.downloadImageFromWeb(urlOfQuoteOftheDay)
        print("Image Fecthed Successfully")

        #Opening the thought of the day image here
        imageName="Thought of the day.jpg"
        attachment=open(imageName,'rb')

        msgImage=MIMEImage(fp.read())
        msgImage.add_header('Content-ID','<image1>')
        msg.Root.attach(msgImage)
        #adding data in the image as a part using MIMBase(don't really know whats happening here)
        #part=MIMEBase('application','octet-stream')
        #part.set_payload(attachment.read())
        #encoders.encode_base64(part)
        #part.add_header('Content-Disposition',"attachement; filename = "+imageName)

        #Attaching Image in the email msg
        #msg.attach(part)
        print("Attaching Image with msg")

        #Attaching body
        #msg.attach(MIMEText(body,'plain'))
        
        print("Attaching message content")

        #Changing msg content into text
        
        contentText=msg.as_string()
        '''
        # Create the root message and fill in the from, to, and subject headers
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = 'Automated test mail | Thought of the day'
        msgRoot['From'] = fromAddress
        msgRoot['To'] = toAddress
        msgRoot.preamble = 'This is a multi-part message in MIME format.'

        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        msgText = MIMEText('This is the alternative plain text message.')
        msgAlternative.attach(msgText)

        # We reference the image in the IMG SRC attribute by the ID we give it below
        msgText = MIMEText('<b><i></i></b><br><img src="cid:image1"><br>',
                           'html')
        msgAlternative.attach(msgText)

        # This example assumes the image is in the current directory
        fp = open('Thought of the day.jpg', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)
        #Contacting gmail server and logging In
        '''
        server=smtplib.SMTP("smtp.gmail.com","587")
        print("Contacting Server")
        server.starttls()
        server.login("*****@*****.**","rohitwalecha")
        print("Loging In")
        '''
        server.sendmail(fromAddress, toAddress, msgRoot.as_string())
        print("Thought of the Day Sent Successfully")

    server.quit()
Example #44
0
    message = MIMEMultipart()
    message['From'] = your_email
    message['To'] = emails[i]
    message['bcc'] = ''  # sir's email address here
    message['Subject'] = ''  #your subject here
    #The subject line
    #The body and the attachments for the mail
    message.attach(MIMEText(mail_content, 'plain'))

    ## images of certificates here
    attachment_path_list = r'd:/internship/images'

    ## images path for new courses here
    img_data1 = open('D:/internship/Code Maze/output-onlinepngtools.png', 'rb')
    ## image name here
    image1 = MIMEImage(img_data1.read(),
                       name=os.path.basename('output-onlinepngtools.png'))
    message.attach(image1)

    for files in os.listdir(attachment_path_list):

        if files.startswith(name):
            print(files, name)
            img_data2 = open(attachment_path_list + '/' + files, 'rb').read()
            image1 = MIMEImage(img_data2, name=os.path.basename(files))
    message.attach(image1)
    try:
        # sending the email
        server.sendmail(your_email, email, message.as_string())
        print('Email to ', email, ' successfully sent!')
    except Exception as e:
        print('Email to ', email, ' could not be sent')
Example #45
0
def send_email_smtp(  # pylint: disable=invalid-name,too-many-arguments,too-many-locals
    to: str,
    subject: str,
    html_content: str,
    config: Dict[str, Any],
    files: Optional[List[str]] = None,
    data: Optional[Dict[str, str]] = None,
    images: Optional[Dict[str, bytes]] = None,
    dryrun: bool = False,
    cc: Optional[str] = None,
    bcc: Optional[str] = None,
    mime_subtype: str = "mixed",
) -> None:
    """
    Send an email with html content, eg:
    send_email_smtp(
        '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
    """
    smtp_mail_from = config["SMTP_MAIL_FROM"]
    smtp_mail_to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg["Subject"] = subject
    msg["From"] = smtp_mail_from
    msg["To"] = ", ".join(smtp_mail_to)
    msg.preamble = "This is a multi-part message in MIME format."

    recipients = smtp_mail_to
    if cc:
        smtp_mail_cc = get_email_address_list(cc)
        msg["CC"] = ", ".join(smtp_mail_cc)
        recipients = recipients + smtp_mail_cc

    if bcc:
        # don't add bcc in header
        smtp_mail_bcc = get_email_address_list(bcc)
        recipients = recipients + smtp_mail_bcc

    msg["Date"] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, "html")
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, "rb") as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename,
                )
            )

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(
                body, Content_Disposition="attachment; filename='%s'" % name, Name=name
            )
        )

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, imgdata in (images or {}).items():
        image = MIMEImage(imgdata)
        image.add_header("Content-ID", "<%s>" % msgid)
        image.add_header("Content-Disposition", "inline")
        msg.attach(image)

    send_mime_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
Example #46
0
def mail(target_date, tmp_path):
    if not (SES_REGION and MAIL_FROM and MAIL_TO):
        return
    ses = AWS_SESSION.client('ses', SES_REGION)
    lvea = ses.list_verified_email_addresses()
    if MAIL_FROM not in lvea['VerifiedEmailAddresses']:
        print(f'Not Verified: {MAIL_FROM} in {lvea["VerifiedEmailAddresses"]}')
        return

    msg = MIMEMultipart('mixed')
    msg['Subject'] = f'[eneos-denki] {target_date.strftime("%Y-%m-%d")}'
    msg['From'] = MAIL_FROM
    msg['To'] = MAIL_TO
    msg_body = MIMEMultipart('alternative')
    textpart = MIMEText('画像'.encode('utf-8'), 'plain', 'utf-8')
    htmlpart = MIMEText(
        f'''
        <p><img src="cid:hourly"/></p>
        <p><img src="cid:daily"/></p>
    '''.encode('utf-8'), 'html', 'utf-8')
    msg_body.attach(textpart)
    msg_body.attach(htmlpart)
    msg.attach(msg_body)

    p = tmp_path + 'hourly.png'
    att = MIMEImage(open(p, 'rb').read(), 'png')
    att.add_header('Content-ID', '<hourly>')
    att.add_header('Content-Disposition',
                   'attachment',
                   filename=os.path.basename(p))
    msg.attach(att)
    p = tmp_path + 'daily.png'
    att = MIMEImage(open(p, 'rb').read(), 'png')
    att.add_header('Content-ID', '<daily>')
    att.add_header('Content-Disposition',
                   'attachment',
                   filename=os.path.basename(p))
    msg.attach(att)

    response = ses.send_raw_email(
        Source=MAIL_FROM,
        Destinations=MAIL_TO.split(','),
        RawMessage={'Data': msg.as_string()},
    )
    return response
Example #47
0
def get_image(image):
    mime_image = MIMEImage(image.read())
    mime_image.add_header('Content-ID', '<image>')
    return mime_image
Example #48
0
def email_guest_booking_confirmation(booking_details):
    gmailHttp = OAUTH2.http()
    gmailService = apiclient.discovery.build('gmail', 'v1', http=gmailHttp)

    strFrom = 'me'
    strTo = booking_details['email']

    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Booking Confirmation'
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText(
        'This email is only available to read in HTML format. Please switch your email viewing mode to HTML to read this email.'
    )
    msgAlternative.attach(msgText)

    body = get_booking_confirmation_email_body(booking_details)
    if is_already_paid(booking_details):
        body = get_booking_confirmation_email_no_payment_body(booking_details)

    # This example assumes the image is in the current directory
    fp = open('./bookings/static/images/logo_medium.jpg', 'rb')
    msgImage = MIMEImage(fp.read(), _subtype="jpg")
    fp.close()

    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '<image2>')
    msgRoot.attach(msgImage)

    fp = open('./bookings/static/images/header_large.jpg', 'rb')
    msgImage = MIMEImage(fp.read(), _subtype="jpg")
    fp.close()

    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)

    if is_already_paid(
            booking_details
    ):  # airbnb email viewer does not display PDF, so include TnC in text.
        body += get_pseudo_pdf_attachment_body()
    else:
        attachment_path = "./bookings/static/pdf/foo.pdf"

        with open(attachment_path) as pdf_file:
            pdf = MIMEApplication(pdf_file.read(), _subtype='pdf')
            pdf.add_header('content-disposition',
                           'attachment',
                           filename=basename(attachment_path))

        msgRoot.attach(pdf)

    msgText = MIMEText(body.encode('utf-8'), 'html', 'utf-8')
    msgAlternative.attach(msgText)

    msg = {'raw': base64.urlsafe_b64encode(msgRoot.as_string())}

    results = gmailService.users().messages().send(
        userId='me', body=msg).execute(http=gmailHttp)
    return results
Example #49
0
                msg.preamble = 'Scanned using hp-scan'

                if email_note:
                    txt = MIMEText(email_note)
                    msg.attach(txt)

                if file_saved:
                    txt = MIMEText("attached: %s: %dx%d %s PNG image." %
                        (os.path.basename(output), pixels_per_line, lines, scan_mode))
                else:
                    txt = MIMEText("attached: %dx%d %s PNG image." % (pixels_per_line, lines, scan_mode))

                msg.attach(txt)

                fp = open(output, 'r')
                img = MIMEImage(fp.read())
                fp.close()

                if file_saved:
                    img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(output))

                msg.attach(img)

                sendmail = utils.which("sendmail")

                if sendmail:
                    sendmail = os.path.join(sendmail, 'sendmail')
                    cmd = [sendmail,'-t','-r',email_from]

                    log.debug(repr(cmd))
                    err = None
Example #50
0
    mm['From'] = "{}<{}>".format(args.sender[0], args.sender[1])
    mm['To'] = "{}<{}>".format(args.receiver[0], args.receiver[1])
    mm['subject'] = Header(args.subject, 'utf-8')

    # Attach text
    mesg = MIMEText(args.text, 'plain', 'utf-8')
    mm.attach(mesg)

    # Attach images.
    if args.image is not None:
        for file in args.image:
            with open(file, 'rb') as im:
                mimetype, encoding = guess_type(file)
                maintype, subtype = mimetype.split('/')
                mimeim = MIMEImage(im.read(), **{'_subtype': subtype})
            _, name_with_ext = osp.split(file)
            mimeim['Content-Disposition'] = \
                'attachment;filename={}'.format(name_with_ext)
            mm.attach(mimeim)

    # Attach excels.
    if args.excel is not None:
        for file in args.excel:
            with open(file, 'rb') as txt:
                mimetxt = MIMEText(txt.read(), 'base64', 'utf-8')
            _, name_with_ext = osp.split(file)
            mimetxt['Content-Disposition'] = \
                'attachment;filename={}'.format(name_with_ext)
            mm.attach(mimetxt)
Example #51
0
def send_mail(dest, itemType, get_graph, key):
    # Mail settings | Configrações de e-mail ###########################################################################
    mail_from = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionEmail', 'mail.from')
    smtp_server0 = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionEmail', 'smtp.server')
    mail_user0 = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionEmail', 'mail.user')
    mail_pass0 = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionEmail', 'mail.pass')
    ####################################################################################################################

    try:
        smtp_server = decrypt(key, smtp_server0)
    except:
        smtp_server = smtp_server0

    try:
        mail_user = decrypt(key, mail_user0)
    except:
        mail_user = mail_user0

    try:
        mail_pass = decrypt(key, mail_pass0)
    except:
        mail_pass = mail_pass0

    try:
        mail_from = email.utils.formataddr(
            tuple(mail_from.replace(">", "").split(" <")))
    except:
        mail_from = mail_from

    dests = ', '.join(dest)
    msg = body
    msg = msg.replace("\\n", "").replace("\n", "<br>")
    try:
        subject = re.sub(r"(<(\/)?[a-z]>)", "", sys.argv[2])
    except:
        subject = sys.argv[2]

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = mail_from
    msgRoot['To'] = dests

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    saudacao = salutation
    Saudacao = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionEmail', 'salutation.email')

    if re.search("(sim|s|yes|y)", str(Saudacao).lower()):
        if saudacao:
            saudacao = "<p>{0},</p>".format(salutation)
    else:
        saudacao = ""

    text = '{0}<p>{1}</p>'.format(saudacao, msg)

    if re.search("(0|3)", itemType):
        URL = "{0}/history.php?action=showgraph&itemids[]={1}"
        text += '<br><a href="{0}"><img src="cid:image1"></a>'.format(
            URL.format(zbx_server, itemid))
        msgImage = MIMEImage(get_graph.content)
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)

    msgText = MIMEText(text, 'html', _charset='utf-8')
    msgAlternative.attach(msgText)

    try:
        smtp = smtplib.SMTP(smtp_server)
        smtp.ehlo()

        try:
            smtp.starttls()
        except Exception:
            pass

        try:
            smtp.login(mail_user, mail_pass)
        except smtplib.SMTPAuthenticationError as msg:
            # print("Error: Unable to send email | Não foi possível enviar o e-mail - {0}".format(msg.smtp_error.decode("utf-8").split(". ")[0]))
            log.writelog(
                'Error: Unable to send email | Não foi possível enviar o e-mail - {0}'
                .format(msg.smtp_error.decode("utf-8").split(". ")[0]), arqLog,
                "WARNING")
            smtp.quit()
            exit()
        except smtplib.SMTPException:
            pass

        try:
            smtp.sendmail(mail_from, dest, msgRoot.as_string())
        except Exception as msg:
            # print("Error: Unable to send email | Não foi possível enviar o e-mail - {0}".format(msg.smtp_error.decode("utf-8").split(". ")[0]))
            log.writelog(
                'Error: Unable to send email | Não foi possível enviar o e-mail - {0}'
                .format(msg.smtp_error.decode("utf-8").split(". ")[0]), arqLog,
                "WARNING")
            smtp.quit()
            exit()

        if re.search("(sim|s|yes|y)", str(Ack).lower()):
            if nograph not in argvs:
                ack(dests, "Email enviado com sucesso ({0})")

        # print("Email sent successfully | Email enviado com sucesso ({0})".format(dests))
        log.writelog(
            'Email sent successfully | Email enviado com sucesso ({0})'.format(
                dests), arqLog, "INFO")
        smtp.quit()
    except smtplib.SMTPException as msg:
        # print("Error: Unable to send email | Não foi possível enviar o e-mail ({0})".format(msg))
        log.writelog(
            'Error: Unable to send email | Não foi possível enviar o e-mail ({0})'
            .format(msg), arqLog, "WARNING")
        logout_api()
        smtp.quit()
        exit()
Example #52
0
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + h, y + w), (0, 255, 0),
                          2)  #0,255,0
            #max_face=w*h
            result = (x, y, w, h)
            x = result[0]
            y = result[1]

        #避免在短时间内重复拍摄,设置时间戳
        if currentDate - sendDate > 600:
            cv2.imwrite("out.png", frame)

            img_file = open('out.png', "rb")
            img_data = img_file.read()
            img_file.close()
            img = MIMEImage(img_data)
            img.add_header('Content-ID', '0')  #正常附件的header是不同的
            msg.attach(img)
            msg["From"] = Header("CLB", "utf-8")
            msg["To"] = Header(receiver, "utf-8")
            msg["Subject"] = Header("face detected", "utf-8")
            #-----------------将图片作为正文内容添加-------------------
            message = MIMEText(
                "<p>careful!!!!!</p><p>human approach your device</p><img src='cid:0'/>",
                "html", "utf-8")  #plain表示纯文本
            msg.attach(message)
            contype = 'application/octet-stream'
            maintype, subtype = contype.split('/', 1)
            try:
                #qq必须要用.SMTP_SSL
                #其他服务器try:.SMTP
Example #53
0
    <br/><br/>

    <h1> Ads insertados por País </h1>
    {country_data}
    """.format(category_data = category_html, country_data = country_html)


email_host = ""
email_user = ""
email_password = ""

# instantiate a SMTP class
email_server = smtplib.SMTP(email_host)

# If a user and password is provided, we need to login
if(email_user and email_password):
    email_server.login(email_user, email_password)


msg = MIMEMultipart()

msg['Subject'] = "Reporte semanal"
msg['From'] = ""
msg['To'] = ""

msg.attach(MIMEImage(open("cat.png", 'rb').read()))
msg.attach(MIMEImage(open("country.png", 'rb').read()))
msg.attach(MIMEText(content, 'html'))

email_server.send_message(msg)
Example #54
0
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=None,
                                  mimeSubtype="plain",
                                  _threadId=None):
    """Creates a MIMEText object and returns it as a base64 encoded string in a ``{'raw': b64_MIMEText_object}``
    dictionary, suitable for use by ``_sendMessage()`` and the ``users.messages.send()`` Gmail API. File attachments can
    also be added to this message.

    The ``sender``, ``recipient``, ``subject``, ``body`` arguments are strings.

    The ``attachments`` argument is a list of strings of filenames.

    The ``cc`` and ``bcc`` arguments are strings with comma-delimited email addresses.

    Note that the ``sender`` argument seems to be ignored by Gmail, which uses the account's actual email address.
    """
    if not isinstance(mimeSubtype, str):
        raise EZGmailTypeError(
            'wrong type passed for mimeSubtype arg; must be "plain" or "html"')
    mimeSubtype = mimeSubtype.lower()
    if mimeSubtype not in ("html", "plain"):
        raise EZGmailValueError(
            'wrong string passed for mimeSubtype arg; mimeSubtype arg must be "plain" or "html"'
        )

    message = MIMEMultipart()
    message["to"] = recipient
    message["from"] = sender
    message["subject"] = subject
    if cc is not None:
        message["cc"] = cc
    if bcc is not None:
        message["bcc"] = bcc

    messageMimeTextPart = MIMEText(body, mimeSubtype)
    message.attach(messageMimeTextPart)

    if isinstance(attachments, str):
        attachments = [attachments
                       ]  # If it's a string, put ``attachments`` in a list.

    for attachment in attachments:
        # Check that the file exists.
        if not os.path.exists(attachment):
            raise EZGmailException(
                "%r passed for attachment but %s does not exist." %
                (attachment, os.path.abspath(attachment)))

        content_type, encoding = mimetypes.guess_type(attachment)

        if content_type is None or encoding is not None:
            content_type = "application/octet-stream"
        main_type, sub_type = content_type.split("/", 1)

        if main_type == "text":
            fp = open(attachment, "r")
            mimePart = MIMEText(fp.read(), _subtype=sub_type)
        else:
            fp = open(attachment, "rb")
            if main_type == "image":
                mimePart = MIMEImage(fp.read(), _subtype=sub_type)
            elif main_type == "audio":
                mimePart = MIMEAudio(fp.read(), _subtype=sub_type)
            else:
                mimePart = MIMEBase(main_type, sub_type)
                mimePart.set_payload(fp.read())
                encoders.encode_base64(mimePart)
        fp.close()

        filename = os.path.basename(attachment)
        mimePart.add_header("Content-Disposition",
                            "attachment",
                            filename=filename)
        message.attach(mimePart)

    rawMessage = {
        "raw": base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")
    }
    if _threadId is not None:
        rawMessage['threadId'] = _threadId
    return rawMessage
Example #55
0
def send_email(subject, text, to, html="", reply_email=''):
    from_email = settings.FROM_EMAIL

    mail = EmailMultiAlternatives(subject=subject,
                                  body=text,
                                  from_email=from_email,
                                  to=to)

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = from_email
    msgRoot['To'] = ', '.join(to)

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
    msgAlternative.attach(msgText)

    links = re.compile("<img[^>]*\ssrc=\"(.*?)\"").findall(html)
    media_root = settings.MEDIA_ROOT
    static_root = settings.STATIC_ROOT
    for i, link in enumerate(links):
        try:
            name = 'image%s' % i
            html = html.replace(link, 'cid:%s' % name)
            link = urllib.parse.unquote(link)
            if '/media/' in link and not link.startswith('/media/'):
                link = '/media/' + link.split('/media/')[1]
            elif '/static/' in link and not link.startswith('/static/'):
                link = '/static/' + link.split('/static/')[1]
            if '/media/' in link:
                path = os.path.join(media_root, link.split('/media/')[-1])
            elif '/static/' in link:
                path = os.path.join(static_root, link.split('/static/')[-1])
            fp = open(path, 'rb')
            msgImage = MIMEImage(fp.read(), _subtype=path.split('.')[-1])
            fp.close()

            msgImage.add_header('Content-ID', '<%s>' % name)
            msgRoot.attach(msgImage)
        except Exception as e:
            pass

    msgText = MIMEText(html.encode('UTF-8'), 'html', 'UTF-8')
    msgAlternative.attach(msgText)

    if to:
        try:
            use_gmail = getattr(settings, 'USE_GMAIL_SMTP', False)
            if use_gmail:
                smtp = smtplib.SMTP(settings.EMAIL_HOST)
                smtp.starttls()
            else:
                smtp = smtplib.SMTP()
                smtp.connect(settings.EMAIL_HOST)
            smtp.login(str(settings.EMAIL_HOST_USER),
                       str(settings.EMAIL_HOST_PASSWORD))
            smtp.sendmail(msgRoot['From'], to, msgRoot.as_string())
            smtp.quit()
        except:
            mail.attach_alternative(html, "text/html")
            mail.send(fail_silently=True)
Example #56
0
def send_gmail_withattachments(fromaddr='',
                               password_pointer='',
                               toaddrs=[],
                               plainmsg='',
                               files=[]):
    result = False
    try:
        username = fromaddr
        print("\nSending email from %s..." % fromaddr)
        if (os.path.isfile(password_pointer) == True):
            password = open(password_pointer, 'r', encoding='utf8').readline()
        else:
            password = password_pointer

        COMMASPACE = ', '

        # Create the container (outer) email message.
        msg = MIMEMultipart()
        msg['Subject'] = plainmsg
        # me == the sender's email address
        # family = the list of all recipients' email addresses
        msg['From'] = fromaddr
        msg['To'] = COMMASPACE.join(toaddrs)
        msg.preamble = plainmsg

        for file in files:

            ctype, encoding = mimetypes.guess_type(file)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)

            print("Attaching file of type: ", maintype, ", subtype: ", subtype)

            if maintype == "text":
                fp = open(file)
                # Note: we should handle calculating the charset
                attachment = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "image":
                fp = open(file, "rb")
                attachment = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "audio":
                fp = open(file, "rb")
                attachment = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(file, "rb")
                attachment = MIMEBase(maintype, subtype)
                attachment.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition",
                                  "attachment",
                                  filename=file)
            msg.attach(attachment)

        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(username, password)
        server.send_message(msg)
        server.quit()
        result = True
        print("Email sent successfully from %s" % (fromaddr))
        return (result)
    except:
        traceback.print_exc()
        print("Error encountered sending email from %s" % (fromaddr))
        return (result)
Example #57
0
from email.mime.text import MIMEText
import smtplib
 
# create message object instance
msg = MIMEMultipart()
 
 
# setup the parameters of the message
password = '******' #Introducir password
msg['From'] = '*****@*****.**'
msg['To'] = '*****@*****.**'
msg['Subject'] = 'Envio foto con Python'
 
# attach image to message body
filefoto = open('D:\\Curso Python MC\\RaspberryPi\\Hoja_09\\Ej_Extra\\fotoCarolDani.jpg', 'rb')
msg.attach(MIMEImage(filefoto.read()))

# attach text to message body
body = 'Buenas Ignacio,\nEjercicio extra de la hoja 9 by Carol & Dani'
msg.attach(MIMEText(body, 'plain'))
 
# create server
server = smtplib.SMTP('smtp.office365.com: 587')
 
server.starttls()

# Login Credentials for sending the mail
server.login(msg['From'], password)
 
 
# send the message via the server.
    #with open('./xml/' + rcp_no + '.xml', 'rb') as opened:
    #    openedfile = opened.read()
    #attachedfile = MIMEApplication(openedfile, _subtype = "pdf")
    #attachedfile.add_header('content-disposition', 'attachment', filename = rcp_no + '.xml')
    #msg.attach(attachedfile)
    gongsi_href = '<a href=' + '"http://dart.fss.or.kr/dsaf001/main.do?rcpNo=' + rcp_no + '">공시 전문으로 이동</a>'
    mail_text = crp_nm + ' 사업보고서 임직원 현황 시각화 테스트중' + '<br>' + gongsi_href
    #이미지첨부
    for no in range(1, 6):
        img = dict(path='chart/' + rcp_no + '__' + str(no) + '.jpg',
                   cid=str(uuid.uuid4()))
        mail_text += u'<div dir="ltr">' '<img src="cid:{cid}" alt="{alt}"></div>'.format(
            alt=cgi.escape(img['path'], quote=True), **img)
        try:
            with open(img['path'], 'rb') as file:
                msg_image = MIMEImage(file.read(),
                                      name=os.path.basename(img['path']))
                msg_image.add_header('Content-ID', '<{}>'.format(img['cid']))
            msg.attach(msg_image)
        except:
            pass

    mail_text = MIMEText(mail_text, 'html', 'utf-8')
    msg_alternative.attach(mail_text)

    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login("m.robo.walt", "***")
    mailServer.sendmail('*****@*****.**', reciplist, msg.as_string())
    mailServer.quit()
Example #59
0
    def create(self):
        '''
            create message to send with send message
        '''

        for attachment in self.__messageAttachment:
            part = None
            f = None
            
            if attachment.get('type') == 'application':
                f = open(attachment.get('file'), 'rb')
                part = MIMEApplication(
                    f.read(),
                    attachment.get('mimeType'),
                    attachment.get('encoder'),
                    **attachment.get('param'))
                    
            elif attachment.get('type') == 'image':
                f = open(attachment.get('file'), 'rb')
                part = MIMEImage(
                    f.read(),
                    attachment.get('mimeType'),
                    attachment.get('encoder'),
                    **attachment.get('param'))
            
            elif attachment.get('type') == 'audio':
                f = open(attachment.get('file'), 'rb')
                part = MIMEAudio(
                    f.read(),
                    attachment.get('mimeType'),
                    attachment.get('encoder'),
                    **attachment.get('param'))
            
            elif attachment.get('type') == 'base':
                f = open(attachment.get('file'), 'rb')
                part = MIMEBase(
                    attachment.get('mimeMain'),
                    attachment.get('mimeType'))
                part.set_payload(open(attachment.get('file'), "rb").read())
                attachment.get('encoder')(part)
                    
            elif attachment.get('type') == 'message':
                part = MIMEMessage(
                    attachment.get('msg'),
                    attachment.get('mimeType'))
                                    
            elif attachment.get('type') == 'text':
                if os.path.isfile(attachment.get('file')):
                    f = open(attachment.get('file'), 'rb')
                    part = MIMEText(
                        f.read(),
                        attachmentEncoders.encode_base64.get('mimeType'),
                        attachment.get('charset'))
                        
                else:
                    part = MIMEText(
                        attachment.get('file'),
                        attachment.get('mimeType'),
                        attachment.get('charset'))
            
            if part:            
                if attachment.get('disposition') and f:
                    part.add_header('Content-Disposition', 'attachment; filename="' + f.name + '"')
                    
                self.__message.attach(part)

            if f:
                f.close()

        message = deepcopy(self.__message)
        self.clear()

        return message
Example #60
0
def main():
    parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_option('-d',
                      '--directory',
                      type='string',
                      action='store',
                      help="""Mail the contents of the specified directory,
                      otherwise use the current directory.  Only the regular
                      files in the directory are sent, and we don't recurse to
                      subdirectories.""")
    parser.add_option('-o',
                      '--output',
                      type='string',
                      action='store',
                      metavar='FILE',
                      help="""Print the composed message to FILE instead of
                      sending the message to the SMTP server.""")
    parser.add_option('-s',
                      '--sender',
                      type='string',
                      action='store',
                      metavar='SENDER',
                      help='The value of the From: header (required)')
    parser.add_option('-r',
                      '--recipient',
                      type='string',
                      action='append',
                      metavar='RECIPIENT',
                      default=[],
                      dest='recipients',
                      help='A To: header value (at least one required)')
    opts, args = parser.parse_args()
    if not opts.sender or not opts.recipients:
        parser.print_help()
        sys.exit(1)
    directory = opts.directory
    if not directory:
        directory = '.'
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    outer['To'] = COMMASPACE.join(opts.recipients)
    outer['From'] = opts.sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # 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(path)
        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(path)
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)
    # Now send or store the message
    composed = outer.as_string()
    if opts.output:
        fp = open(opts.output, 'w')
        fp.write(composed)
        fp.close()
    else:
        s = smtplib.SMTP()
        s.sendmail(opts.sender, opts.recipients, composed)
        s.quit()