Example #1
1
def mail(receiver, subject, abs_path_files):

    send_addr = '*****@*****.**'
    password = '******'

    msg = MIMEMultipart()
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = send_addr
    if isinstance(abs_path_files, str):
        single_file = list()
        single_file.append(abs_path_files)
        abs_path_files = single_file
    for file in abs_path_files:
        file_name = os.path.basename(file)
        att = MIMEBase('application', 'octet-stream', filename=file)
        att.add_header('Content-disposition', 'attatchment', filename=('utf-8', '', file))
        att.set_payload(open(file, 'rb').read())
        encoders.encode_base64(att)
        msg.attach(att)

    # 发送邮件
    smtp = smtplib.SMTP('smtp.exmail.qq.com', 587)
    smtp.starttls()
    smtp.login(send_addr, password)
    smtp.sendmail(send_addr, receiver, msg.as_string())
    smtp.quit()
Example #2
0
 def addAttachments(self, message, Attachments):
     for item in Attachments:
         dtemp = tempfile.mkdtemp()
         tempAttach = os.path.join(dtemp, 'tempAttach')
         item.SaveAsFile(tempAttach)
         attachment = MIMEBase('application', 'octet-stream')
         try:
             fp = open(tempAttach, 'rb')
             attachment.set_payload(fp.read())
             fp.close()
             encoders.encode_base64(attachment)
             fname = item.DisplayName.encode(OutlookCharset, errors='ignore')
             attachment.add_header(
                 'Content-Disposition',
                 'attachment',
                 filename=fname
             )
             message.attach(attachment)
             os.remove(tempAttach)
             os.rmdir(dtemp)
         except IOError, e:
             # Some attachements are URLs to outside files
             # The result is a "tempAttach.url" file, with the link to attachement
             # Open fails on this type of file
             # Leaving a temporary file and directory is not clean
             # TODO Clean this mess
             pass
def send_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT):
    assert isinstance(to_, (list, tuple))

    if files is None:
        files = []

    msg = MIMEMultipart()
    msg['From'] = _from_
    msg['To'] = COMMASPACE.join(to_)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file_name, file_content in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( file_content )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % file_name)
        msg.attach(part)

    smtp = smtplib.SMTP(server, port=port)
    smtp.sendmail(_from_, to_, msg.as_string() )
    smtp.close()
Example #4
0
    def send_raw_email(self, **kwargs):
        ''' still in dev '''
        msg_all = MIMEMultipart()
        msg_all['From'] = kwargs['source']
        msg_all['To'] = kwargs['to_addresses']
        msg_all['Subject'] = kwargs['subject']

        msg_all.attach(MIMEText("""123國<br><a href="http://toomore.net/">link</a>""", 'html', 'utf-8'))

        ics = render_ics(
            title=u'吃火鍋',
            description=u'冬天到了要吃火鍋!',
            location=u'台北市中正區衡陽路51號',
            start=datetime(2015, 1, 29, 10),
            end=datetime(2015, 1, 29, 18, 30),
            created=None,
            admin=u'Toomore',
            admin_mail=u'*****@*****.**',
            url=u'http://toomore.net/'
        )
        attachment = MIMEBase('text', 'calendar; name=calendar.ics; method=REQUEST; charset=UTF-8')
        attachment.set_payload(ics.encode('utf-8'))
        encoders.encode_base64(attachment)
        attachment.add_header('Content-Disposition', 'attachment; filename=%s' % "calendar.ics")

        msg_all.attach(attachment)

        return super(AwsSESTools, self).send_raw_email(msg_all.as_string(), kwargs['source'])
Example #5
0
    def create_part(key, fileobject, content_type, multiple=False):
        """Create and return a multipart part as to given file data.

        key -- Field name.
        fileobject -- The file-like object to add to the part.
        content_type -- Content-type of the file. If None, use default.
        multiple -- If true, use Content-Disposition: file.

        """
        if not content_type:
            content_type = DEFAULT_CONTENT_TYPE
        (maintype, subtype) = content_type.split("/")
        part = MIMEBase(maintype, subtype)
        part.set_payload(fileobject.read())
        encode_base64(part)
        filename = getattr(fileobject, "name", None)
        kwargs = dict()
        if multiple:
            # RFC 2388 Returning Values from Forms: multipart/form-data
            # The original local file name may be supplied as well, either as
            # a "filename" parameter either of the "content-disposition: 
            # form-data" header or, in the case of multiple files, in a
            # "content-disposition: file" header of the subpart.
            kwargs["disposition"] = "file"
        add_disposition(part, key, filename, **kwargs)
        return part
    def __init__(self, _subtype='mixed', boundary=None, _subparts=None,
                 **_params):
        """Creates a multipart/* type message.

        By default, creates a multipart/mixed message, with proper
        Content-Type and MIME-Version headers.

        _subtype is the subtype of the multipart content type, defaulting to
        `mixed'.

        boundary is the multipart boundary string.  By default it is
        calculated as needed.

        _subparts is a sequence of initial subparts for the payload.  It
        must be an iterable object, such as a list.  You can always
        attach new subparts to the message by using the attach() method.

        Additional parameters for the Content-Type header are taken from the
        keyword arguments (or passed into the _params argument).
        """
        MIMEBase.__init__(self, 'multipart', _subtype, **_params)
        if _subparts:
            for p in _subparts:
                self.attach(p)
        if boundary:
            self.set_boundary(boundary)
Example #7
0
    def _get_mime_object(self, content_string):
        content_object = {
            'mime_object': None,
            'encoding': None,
            'main_type': None,
            'sub_type': None
        }
        if isinstance(content_string, dict):
            for x in content_string:
                content_string, content_name = x, content_string[x]
        else:
            content_name = os.path.basename(content_string)

        # pylint: disable=unidiomatic-typecheck
        is_raw = type(content_string) == raw
        if not is_raw:
            content_string = content_string.encode('utf-8')
            if os.path.isfile(content_string):
                with open(content_string, 'rb') as f:
                    content_object['encoding'] = 'base64'
                    content = f.read()
        else:
            content_object['main_type'] = 'text'
            try:
                if not is_raw:
                    html_tree = lxml.html.fromstring(content_string)
                    if (html_tree.find('.//*') is not None or
                            html_tree.tag != 'p'):
                        content_object['mime_object'] = MIMEText(
                            content_string, 'html', _charset='utf-8')
                        content_object['sub_type'] = 'html'
                if content_object['mime_object'] is None:
                    content_object['mime_object'] = MIMEText(content_string, _charset='utf-8')
            except NameError:
                self.log.error(
                    "Sending as text email since `lxml` is not installed")
                content_object['mime_object'] = MIMEText(content_string, _charset='utf-8')
            if content_object['sub_type'] is None:
                content_object['sub_type'] = 'plain'
            return content_object

        if content_object['main_type'] is None:
            content_type, _ = mimetypes.guess_type(content_string)

            if content_type is not None:
                content_object['main_type'], content_object[
                    'sub_type'] = content_type.split('/')

        if (content_object['main_type'] is None or
                content_object['encoding'] is not None):
            if content_object['encoding'] != 'base64':
                content_object['main_type'] = 'application'
                content_object['sub_type'] = 'octet-stream'

        mime_object = MIMEBase(
            content_object['main_type'], content_object['sub_type'],
            name=content_name)
        mime_object.set_payload(content)
        content_object['mime_object'] = mime_object
        return content_object
Example #8
0
def send(subject, text, sender=SENDER, recipients=[RECIPIENT], attachments={}, smtp_host=SMTP_HOST, encoding=ENCODING):
    # encode all strings in binary strings
    subject = _binary(subject)
    text = _binary(text)
    sender = _binary(sender)
    if not isinstance(recipients, list):
        recipients = [recipients]
    recipients = _binary(recipients)
    # build the message
    message = MIMEMultipart()
    message['Subject'] = subject
    message['From'] = sender
    message['To'] = ', '.join(recipients)
    # attach text part
    message.attach(MIMEText(text, _charset=encoding))
    # attach attachments if any
    for name,filename in attachments.items():
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(filename,"rb").read())
        encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
        message.attach(part)
    smtp = smtplib.SMTP(smtp_host)
    smtp.sendmail(sender, recipients, message.as_string())
    smtp.quit()
Example #9
0
def sendMail(message, encoding='utf-8'):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header(MAIL_TITLE.encode(encoding), encoding)
    msg['From'] = SENDER
    msg['To'] = SENDER
    text = message
    msg.attach(MIMEText(text.encode(encoding), 'html', encoding))
    # Attach file if specified
    if FILE_JOINED:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(FILE_JOINED, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' %
            FILE_JOINED.split("/")[-1])
        msg.attach(part)
    s = smtplib.SMTP(HOST, PORT)
    s.starttls()
    s.login(SENDER, SENDER_PASSWORD)
    try:
        s.sendmail(SENDER, SENDER, msg.as_string())
    except:
        s.quit()
        return  '%s Failed to send mail' % (SENDER)

    s.quit()
    return '%s / mail sent !' % (SENDER)
Example #10
0
 def add_file(self, path):
     attach = MIMEBase("application", "octet-stream")
     with open(path, "rb") as f:
         attach.set_payload(f.read())
     encoders.encode_base64(attach)
     attach.add_header("content-disposition", "attachment", filename=os.path.basename(path))
     self._attachs.append(attach)
Example #11
0
def send_mail(send_from, send_to, subject, text, server, email_password, files=[], hide=False):
    assert type(send_to)==list
    assert type(files)==list
    assert type(hide)==bool

    msg = MIMEMultipart()
    msg['From'] = send_from
    if not hide:
        # Basically BCC the messages by leaving this out.
        msg['To'] = ', '.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtp = smtplib.SMTP_SSL(server, 465)
    smtp.login(send_from, email_password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Example #12
0
def sendemail(templatedir, templatefile, subject, sender, receiver, game, player=None, pdfpath=None):
	try:
		outer = MIMEMultipart()
		outer['Subject'] = subject
		outer['From'] = sender
		outer['To'] = receiver
		outer['Date'] = email.utils.formatdate()
		outer['Message-Id'] = email.utils.make_msgid('hades')
		outer.preamble = ''
		text = MIMEText( str(mailstream(templatedir, templatefile, game=game, player=player)), 'plain', 'utf-8')
		outer.attach(text)
		
		if pdfpath is not None:
			ctype, encoding = mimetypes.guess_type(pdfpath)
			if ctype is None or encoding is not None:
				ctype = 'application/octet-stream'
			maintype, subtype = ctype.split('/', 1)
			fp = open(pdfpath, 'rb')
			attach = MIMEBase(maintype, subtype)
			attach.set_payload(fp.read())
			fp.close()
			encoders.encode_base64(attach)
			attach.add_header('Content-Disposition', 'attachment', filename='auftrag.pdf')
			outer.attach(attach)
		
		s = smtplib.SMTP('localhost')
		s.sendmail(sender, [receiver], outer.as_string())
		s.quit()
	except Exception as e:
		errprint("ERROR: Cannot send mail to receiver %s" % receiver)
		errprint(e)
		pass
Example #13
0
def prompt_email_and_send(files, type):
	with open('credentials.txt', 'r') as f:
		login_email = f.readline().rstrip()
		login_password = f.readline().rstrip()

	msg = MIMEMultipart()
	
	msg['From'] = login_email
	msg['To'] = input("Your email address?")
	msg['Subject'] = "ADB-script Logs - "+device_name+" - "+type
	
	attachment=zip_attach(files)

	msg.attach(MIMEText("Here are your logs."))
	part = MIMEBase('application', 'octet-stream')
	part.set_payload(open(attachment, 'rb').read())
	encoders.encode_base64(part)
	part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment))
	msg.attach(part)

	try:
		server = smtplib.SMTP('smtp.gmail.com', 587)
		server.ehlo()
		server.starttls()

		server.login(login_email, login_password)
		print("Sending mail... This might take a while.")
		server.sendmail(msg['From'], msg['To'], msg.as_string())
		server.quit()
		print("Successfully sent email.")
	except SMTPException:
		print("Error: unable to send email.")
Example #14
0
	def send_report( self, subject, body, attachment, apptype='x/zip'):
		"""
		Send the email report to its destination.

		@type   to:     string
		@param  to:     Destination email address for the report.
		@type   subject:    string
		@param  subject:    The subject of the email message.
		@type   body:       string
		@param  body:       The body of the email message (includes report summary).
		@type   attachment: string
		@param  attachment: Path to report file for attaching to message.
		@type   apptype:    string
		@param  apptype:    Application MIME type for attachment.
		"""
		message             = MIMEMultipart()
		message['From']     = self.emailfrom
		message['To']       = self.emailto
		message['Subject']  = subject

		message.attach( MIMEText( body ))
		part = MIMEBase('application',apptype)
		part.set_payload( open( attachment, 'r').read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attachment))
		message.attach(part)

		conn = smtplib.SMTP(self.smtpserver, self.smtpport)
		conn.sendmail( message['From'], self.emailto, message.as_string())
		conn.close()
Example #15
0
def send_mail(send_from, send_to, subject, text, files=[]):
    assert isinstance(send_to, list)
    assert isinstance(files, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.login("*****@*****.**", pw)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()
Example #16
0
def derive_email():
    sender = '*****@*****.**' # school email 
    receivers = input("Email address of .zip file recipient: ")
    password = getpass.getpass() #hidden input
    
    message = MIMEMultipart()
    message["From"] = sender
    message["To"] = receivers
    message["Subject"] = "[CSC 344 - Michael Phillips] Assignments Submission" 
    message.attach(MIMEText("This is my submission of the CSC 344 assignments as a .zip file"))
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open("assignments.zip", 'rb').read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename="assignments.zip"')
    message.attach(part)
	
    try:
       smtpObj = smtplib.SMTP("smtp.gmail.com", 587)
       smtpObj.ehlo(); smtpObj.starttls(); smtpObj.ehlo();
       smtpObj.login(sender, password)
       smtpObj.sendmail(sender, receivers, message.as_string())
       smtpObj.close()
       print("Successfully sent email")
    except smtplib.SMTPException:
       print("Error: unable to send email")
Example #17
0
def email():
	hashed="43657166f4c72d25ef02dd2b82afb72b58860f1aeda068a45c2a7353962fb57ffa98db5231457318d6ffae8d6bcd56540f2fd871e3053486edd1e305c571af19"
	#passw= passwd(hashed)
	month="{:%B %Y}".format(datetime.date.today())
	fromaddr = "*****@*****.**"
	toaddr = ['*****@*****.**']
	#toaddr = ['*****@*****.**', '*****@*****.**', '*****@*****.**','*****@*****.**']
	msg = MIMEMultipart()
	msg['From'] = fromaddr
	#msg['To'] = toaddr
	msg['To'] = ",".join(toaddr)
	msg['Subject'] = "Vet Lounge Traffic of %s" % month
	body = "DO NOT reply this email. This is an automatic generated email with traffic data for veterans lounge. Should you have any question, please email [email protected]."
	msg.attach(MIMEText(body, 'plain'))
	filename = "%s.xlsx" %month
	#filename = "August.xlsx" 
	attachment = open("/Users/johnjayveterans/Desktop/summer_project/testing.xlsx", "rb")
	#attachment = open("/Users/garytsai/Desktop/rfid-reader-http/summer_project/testing.xlsx", "rb")
	part = MIMEBase('application', 'octet-stream')
	part.set_payload((attachment).read())
	encoders.encode_base64(part)
	part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
	msg.attach(part)
	server = smtplib.SMTP('smtp.gmail.com', 587)
	server.starttls()
	server.login(fromaddr, "%s" % passwd(hashed))
	text = msg.as_string()
	server.sendmail(fromaddr, toaddr, text)
	server.quit()
Example #18
0
File: mail.py Project: siecj/CAP
def send_mail(fro, to, subject, text, files=[]):
    #assert type(server) == dict 
    assert type(to) == list
    assert type(files) == list
    
    msg = MIMEMultipart('alternative')
    
    msg['Subject'] = subject
    msg['From'] = '*****@*****.**' # Your from name and email address
    msg['To'] = ','.join(to)
    #print msg['To']
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(text, 'html', 'utf-8'))
    
    for file in files:
        data = open(file, 'rb')
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
        part.set_payload(data.read()) 
        data.close()
        encoders.encode_base64(part) 
        part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) 
        msg.attach(part)
        
    s = smtplib.SMTP('10.80.81.132', 25)    
    #s.login(username, password)
    s.sendmail(fro, to, msg.as_string())
    s.quit()
    
    ''' mandrill web api way
Example #19
0
def send_file_zipped(the_file, recipients, sender="*****@*****.**"):
    zf = tempfile.TemporaryFile(prefix="mail", suffix=".zip")
    zip = zipfile.ZipFile(zf, "w")
    zip.write(the_file)
    zip.close()
    zf.seek(0)

    # Create the message
    themsg = MIMEMultipart()
    themsg["Subject"] = "File %s" % the_file
    themsg["To"] = ", ".join(recipients)
    themsg["From"] = sender
    themsg.preamble = "I am not using a MIME-aware mail reader.\n"
    msg = MIMEBase("application", "zip")
    msg.set_payload(zf.read())
    encoders.encode_base64(msg)
    msg.add_header("Content-Disposition", "attachment", filename=the_file + ".zip")
    themsg.attach(msg)
    themsg = themsg.as_string()

    # send the message
    smtp = smtplib.SMTP()
    smtp.connect()
    smtp.sendmail(sender, recipients, themsg)
    smtp.close()
Example #20
0
def create_mail_attachment(attdef, payload=None):
    """Create the MIME part corresponding to the given attachment.

    Mandatory keys: 'fname', 'tmpname', 'content-type'

    :param attdef: a dictionary containing the attachment definition
    :return: a MIMEBase object
    """
    from email import Encoders
    from email.mime.base import MIMEBase

    if "content-type" in attdef:
        maintype, subtype = attdef["content-type"].split("/")
    elif "Content-Type" in attdef:
        maintype, subtype = attdef["Content-Type"].split("/")
    else:
        return None
    res = MIMEBase(maintype, subtype)
    if payload is None:
        with open(os.path.join(
                settings.MEDIA_ROOT, "webmail", attdef["tmpname"]), "rb") as fp:
            res.set_payload(fp.read())
    else:
        res.set_payload(payload)
    Encoders.encode_base64(res)
    if isinstance(attdef['fname'], str):
        attdef['fname'] = attdef['fname'].decode('utf-8')
    res['Content-Disposition'] = build_header(attdef['fname'])
    return res
Example #21
0
def snapshot_email(report_name, filename, data):
    '''
        Send the report to the email account.
    '''

    if not CONFIG['email_id']:
        LOG.info('Skipping email attachment.')
        return
    superman = CONFIG['email_id']
    LOG.info('Attaching report for %s', superman)
    msg = MIMEMultipart()
    msg['Subject'] = '[Pombo report] {0}'.format(report_name)
    msg['From']    = superman
    msg['To']      = superman
    part = MIMEBase('application', 'octet-stream')
    part.add_header('Content-Disposition', 'attachment; filename="{0}"'
                    .format(filename))
    part.set_payload(data)
    encoders.encode_base64(part)
    msg.attach(part)
    try:
        conn = smtplib.SMTP('localhost')
        conn.sendmail(superman, superman, msg.as_string())
        conn.quit()
    except Exception as ex:
        LOG.error(ex)
Example #22
0
    def send(self, destination, subject, content, html_diff, new_file):
        """Send an email with 2 attached html files"""
        server = smtplib.SMTP_SSL(self.host, self.port)
        server.login(self.user, self.password)

        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = self.user
        msg['To'] = destination

        msg.attach(MIMEText(content))

        elems = {
            'diff.html' : html_diff,
            'new.html' : new_file
        }

        for name, content in elems.iteritems():
            m = MIMEBase('text', 'html')
            m.set_payload(content)
            Encoders.encode_base64(m)
            m.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
            msg.attach(m)

        server.sendmail(self.user, destination, msg.as_string())
        server.quit()
Example #23
0
def sendmailError():

    LOG_FILENAME = '/python_scripts/error.txt'
    logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR)
    logging.exception('Error generated on' +' '+ str(datetime.now()))
    logging.debug('Error found. Please read message.')

    msg = MIMEMultipart()
    sender = '*****@*****.**'
    recipient = '*****@*****.**'
    msg['Subject'] = "Error running script"
    msg['From'] = sender 
    msg['To'] = recipient
    attachment = open(LOG_FILENAME, 'rb')

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename= LOG_ERROR.txt')

    msg.attach(part)
    text = msg.as_string()
    s = smtplib.SMTP('xxx.amazonaws.com', 587)
    EMAIL_HOST_USER = '******'
    EMAIL_HOST_PASSWORD = '******'
    s.starttls()
    s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    s.sendmail(sender, recipient, text)
    s.quit()
Example #24
0
 def sendmail(self,recipient = None):
     if not recipient is None:
         self.recipient = recipient
     # set mail type
     send_mail_msg = MIMEMultipart()
     send_mail_msg['Subject'] = self.subject
     send_mail_msg['To'] = self.recipient
     send_mail_msg['From'] = self.mailfrom
     # set mail body
     Contents = MIMEText(self.body.encode('utf-8'),'html','utf-8')
     send_mail_msg.attach(Contents)
     if not self.attach is None:
         # set mail attach
         fp = open(self.attach, "rb")
         attachment = MIMEBase("application", "octet-stream")
         attachment.set_payload(fp.read())
         fp.close()
         encoders.encode_base64(attachment)
         attachment.add_header("Content-Disposition", "attachment", filename=self.attach)
         send_mail_msg.attach(attachment)
     # connect to smtp server
     smtp = smtplib.SMTP(self.smtphost)
     # login smtp
     smtp.login(self.mailfrom,self.password)
     # send mail
     smtp.sendmail(self.mailfrom, self.recipient, send_mail_msg.as_string())
     # quit server
     smtp.quit()
     print "Successfully."
     return
def envia_email(de, para, assunto, mensagem, arquivos, servidor):
	# Cria o objeto da mensagem
   	msg = MIMEMultipart()
   	# Define o cabeçalho
   	msg['From'] = de
   	msg['To'] = para
  	msg['Date'] = formatdate(localtime=True)
   	msg['Subject'] = assunto

   	# Atacha o texto da mensagem
  	msg.attach(MIMEText(mensagem))

   	# Atacha os arquivos
   	for arquivo in arquivos:
      		parte = MIMEBase('application', 'octet-stream')
      		parte.set_payload(open(arquivo, 'rb').read())
      		encoders.encode_base64(parte)
      		parte.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(arquivo))
      		msg.attach(parte)

   	# Conecta ao servidor SMTP
   	smtp = smtplib.SMTP(servidor, 587)
   	smtp.ehlo()
   	smtp.starttls()
   	smtp.ehlo()
	# Faz login no servidor
	smtp.login('*****@*****.**', 'galaxy_fCfRp')
	# Envia o e-mail
	smtp.sendmail(de, para, msg.as_string())
	# Desconecta do servidor
	smtp.close()
Example #26
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()
Example #27
0
  def send(self):
    if(not os.path.isfile(self.exportFile)):
      return

    msg = MIMEMultipart()
    #msg = EmailMessage()
    #msg['Subject'] = 'Export %s' % datetime.now().isoformat()
    msg['Subject'] = 'Export plugin.video.streams'
    msg['From'] = addon.getSetting('smtpUsername')
    msg['To'] = SETTINGS.EXPORT_EMAIL
    #msg.set_content(fp.read())
        
    fp=open(self.exportFile,"rb")
    attach = MIMEBase('application', 'json')
    attach.set_payload(fp.read())
    fp.close()
    # Encode the payload using Base64
    #encoders.encode_base64(msg)
    attach.add_header('Content-Disposition', 'attachment', filename='streams.json')
    msg.attach(attach)
    #msg.add_attachment(f.read(),
    #                   maintype='application',
    #                   subtype='json',
    #                   filename='export.json')
    
    try:  
      self.smtp.sendmail(addon.getSetting('smtpUsername'), SETTINGS.EXPORT_EMAIL, msg.as_string())
      #s.send_message(msg)
    except Exception as inst:
      addon_log(inst)
      xbmcgui.Dialog().ok(addon.getLocalizedString(30300), addon.getLocalizedString(30409), str(inst))
Example #28
0
def send_zipped_file(zipped_file, recipients, sender, connectParams):
    for param in ["host", "port", "user", "pass"]:
        assert param in connectParams, "must specify mandatory parameter %s" % param

    themsg = MIMEMultipart()
    themsg["Subject"] = "TEST: File %s" % zipped_file
    themsg["To"] = ", ".join(recipients)
    themsg["From"] = sender
    themsg.preamble = "I am not using a MIME-aware mail reader.\n"
    with open(zipped_file, "w+") as zf:
        # Create the message
        msg = MIMEBase("application", "zip")
        msg.set_payload(zf.read())
        encoders.encode_base64(msg)
        msg.add_header("Content-Disposition", "attachment", filename=zipped_file)
        themsg.attach(msg)
    themsg = themsg.as_string()

    # send the message
    server = smtplib.SMTP(connectParams["host"], connectParams["port"])
    server.ehlo()
    server.starttls()
    server.login("*****@*****.**", "Opensesami0114")

    server.sendmail(sender, recipients, themsg)
    server.quit()
Example #29
0
    def _create_message_instance(self, subject='', to='', cc='', bcc='', additional_content=''):
        import pprint
        new_message_wrapper = MIMEMultipart('mixed')

        new_message_wrapper["Subject"] = subject

        new_message_wrapper["To"] = to
        new_message_wrapper["Cc"] = cc
        new_message_wrapper["Bcc"] = bcc

        new_message_wrapper['In-Reply-To'] = self._message_id
        new_message_wrapper['References'] = self._message_id

        # check if the message is initially read
        initially_read = self.is_read
        try:
            # fetch the data its a dictionary from uid to data so extract the data
            response = self._imap_client.fetch(
                self._uid, ['RFC822'])  # type: t.Dict[t.AnyStr, t.Any]
            if self._uid not in response:
                raise RuntimeError('Invalid response missing UID')
            response = response[self._uid]

            if 'RFC822' not in response:
                logger.critical('%s:%s response: %s' %
                                (self.folder, self, pprint.pformat(response)))
                logger.critical("%s did not return RFC822" % self)
                raise RuntimeError("Could not find RFC822")

            # text content
            new_message = MIMEMultipart('alternative')

            content = self.content
            separator = "On %s, (%s) wrote:" % (
                datetime.now().ctime(), self._schema.imap_account.email)
            text_content = additional_content + "\n\n" + \
                separator + "\n\n" + (content["text"] if content["text"] else "")
            html_content = additional_content + "<br><br>" + \
                separator + "<br><br>" + (content["html"] if content["html"] else content["text"] or "")

            # We must choose the body charset manually
            for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
                try:
                    text_content.encode(body_charset)
                except UnicodeError:
                    pass
                else:
                    break
            
            # We must choose the body charset manually
            for body_charset2 in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
                try:
                    html_content.encode(body_charset2)
                except UnicodeError:
                    pass
                else:
                    break

            part1 = MIMEText(text_content.encode(body_charset), 'plain', body_charset)
            part2 = MIMEText(html_content.encode(body_charset2), 'html', body_charset2)
            new_message.attach(part1)
            new_message.attach(part2)

            # get attachments
            rfc_contents = email.message_from_string(
                response.get('RFC822'))  # type: email.message.Message

            res = get_attachments(rfc_contents)

            attachments = res['attachments']

            for attachment in attachments:
                p = MIMEBase('application', 'octet-stream')

                # To change the payload into encoded form
                p.set_payload(attachment['content'])

                # encode into base64
                encoders.encode_base64(p)

                p.add_header('Content-Disposition',
                             "attachment; filename= %s" % attachment['filename'])
                new_message_wrapper.attach(p)

            new_message_wrapper.attach(new_message)
        except Exception as e:
            logger.exception ("%s %s" % (e, traceback.format_exc()))
            raise RuntimeError('Failed to deal with a message: %s' % str(e))
            return
        finally:
            # mark the message unread if it is unread
            if not initially_read:
                self.mark_unread()

        return new_message_wrapper
Example #30
0
# Creamos el objeto mensaje
mensaje = MIMEMultipart()
 
# Establecemos los atributos del mensaje
mensaje['From'] = remitente
mensaje['To'] = ", ".join(destinatarios)
mensaje['Subject'] = asunto
 
# Agregamos el cuerpo del mensaje como objeto MIME de tipo texto
mensaje.attach(MIMEText(cuerpo, 'plain'))
 
# Abrimos el archivo que vamos a adjuntar
archivo_adjunto = open(ruta_adjunto, 'rb')
 
# Creamos un objeto MIME base
adjunto_MIME = MIMEBase('application', 'octet-stream')
# Y le cargamos el archivo adjunto
adjunto_MIME.set_payload((archivo_adjunto).read())
# Codificamos el objeto en BASE64
encoders.encode_base64(adjunto_MIME)
# Agregamos una cabecera al objeto
adjunto_MIME.add_header('Content-Disposition', "attachment; filename= %s" % nombre_adjunto)
# Y finalmente lo agregamos al mensaje
mensaje.attach(adjunto_MIME)
 
# Creamos la conexión con el servidor
sesion_smtp = smtplib.SMTP('smtp.gmail.com', 587)
 
# Ciframos la conexión
sesion_smtp.starttls()
Example #31
0
class ChopMailer(object):
    def __init__(self):
        self._sub = ''
        self._sender = '*****@*****.**'
        self.recipients = ''
        self.ccers = ''
        self._smtp = 'mailrouter.chop.edu'
        self._attachment = None
        self._filelocation = None
        self._header = ""
        self._msg = MIMEMultipart('alternative')
        self._body = MIMEText(
            """
    Hello:<br>
    YOU ARE RECEIVING A TEST EMAIL, THIS IS A TEST, and ONLY A TEST!<br/>
    Your requested integrated data report is ready and has been attached.<br>
    If you have any questions please contact Alex Felmeister at [email protected].<br><br>

    Thank you,
    <br>
    The Enterprise Informatics Group<br>
    <a href ="http://dbhi.chop.edu/"><i>The Department of Biomedical and Health Informatics </i></a><br>
    """, 'html')

    def set_header(self, header):
        self._header = header

    def set_recipient(self, recipients):
        """Takes email address as string or list of email addresses. MUST BE IN CHOP DOMAIN"""
        if type(recipients) == str:
            # leave as string for _msg header:
            self._msg['To'] = recipients
            # but put into list form for sendmail():
            self.recipients = recipients.split(",")
            if "@email.chop.edu" not in self.recipients:
                print("All recipients must be on the CHOP domain")
                exit()
        elif type(recipients) == list:
            # put as string for _msg header:
            self._msg['To'] = ", ".join(recipients)
            # and leave in list form for sendmail():
            self.recipients = recipients
            for r in self.recipients:
                if "@email.chop.edu" not in r:
                    print("All recipients must be on the CHOP domain")
                    exit(1)

    # TODO: add catchall else to throw exception for other unexpected types

    def set_subject(self, subject):
        """Use to set Subject. Default subject not set"""
        self._sub = '[SEND SECURE] ' + subject

    def set_body(self, body):
        """Use to overwrite body text with an html block"""
        self._body = MIMEText(body, 'html')

    def set_sender(self, sender):
        """Use to overwrite [email protected]"""
        self._sender = sender

    def set_cc(self, ccers):
        if type(ccers) == str:
            # leave as string for _msg header:
            self._msg['Cc'] = ccers
            # but put into list form for sendmail():
            self.ccers = ccers.split(",")
            if "@email.chop.edu" not in self.ccers:
                print("All cc: recipients must be on the CHOP domain")
                exit()
        elif type(ccers) == list:
            # put as string for _msg header:
            self._msg['Cc'] = ", ".join(ccers)
            # and leave in list form for sendmail():
            self.ccers = ccers
            for r in self.ccers:
                if "@email.chop.edu" not in r:
                    print("All cc: recipients must be on the CHOP domain")
                    exit(1)

    # TODO: add catchall else to throw exception for other unexpected types

    def set_attachment(self, filelocation):
        """Attach CSV file"""
        self._filelocation = filelocation
        with open(self._filelocation) as f:
            self._attachment = MIMEBase('application', 'csv')
            self._attachment.set_payload(f.read())
            self._attachment.add_header('Content-Disposition',
                                        'attachment',
                                        filename=f.name)
            encoders.encode_base64(self._attachment)

    def send(self):
        """Send mail"""
        self._msg['Subject'] = self._sub
        self._msg['From'] = self._sender
        # Now in set_recipient(): self._msg['To'] = self.recipients
        if self._msg['Cc'] is None:
            self._msg['Cc'] = '*****@*****.**'
        # Now in set_cc(): self._msg['Cc'] = self.ccers
        self._msg.attach(self._body)
        if self._attachment:
            self._msg.attach(self._attachment)
        main_engine = smtplib.SMTP(self._smtp)
        try:
            # combine recipients with ccers for all sendmail addresses:
            main_engine.sendmail(self._sender, self.recipients + self.ccers,
                                 self._msg.as_string())
            print("Message Send Successful")
        except:
            print('Message Failed')
Example #32
0
    def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False,
                    attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None,
                    body_alternative=None, subtype_alternative='plain'):
        """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.

           :param string email_from: sender email address
           :param list email_to: list of recipient addresses (to be joined with commas) 
           :param string subject: email subject (no pre-encoding/quoting necessary)
           :param string body: email body, of the type ``subtype`` (by default, plaintext).
                               If html subtype is used, the message will be automatically converted
                               to plaintext and wrapped in multipart/alternative, unless an explicit
                               ``body_alternative`` version is passed.
           :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
           :param string reply_to: optional value of Reply-To header
           :param string object_id: optional tracking identifier, to be included in the message-id for
                                    recognizing replies. Suggested format for object-id is "res_id-model",
                                    e.g. "12345-crm.lead".
           :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
                                  must match the format of the ``body`` parameter. Default is 'plain',
                                  making the content part of the mail "text/plain".
           :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
                                              or 'html'). Default is 'plain'.
           :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
                                    containing the bytes of the attachment
           :param list email_cc: optional list of string values for CC header (to be joined with commas)
           :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
           :param dict headers: optional map of headers to set on the outgoing mail (may override the
                                other headers, including Subject, Reply-To, Message-Id, etc.)
           :rtype: email.message.Message (usually MIMEMultipart)
           :return: the new RFC2822 email message
        """
        email_from = email_from or tools.config.get('email_from')
        assert email_from, "You must either provide a sender address explicitly or configure "\
                           "a global sender address in the server configuration or with the "\
                           "--email-from startup parameter."

        # Note: we must force all strings to to 8-bit utf-8 when crafting message,
        #       or use encode_header() for headers, which does it automatically.

        headers = headers or {}         # need valid dict later
        email_cc = email_cc or []
        email_bcc = email_bcc or []
        body = body or u''

        email_body = ustr(body)
        email_text_part = MIMEText(email_body, _subtype=subtype, _charset='utf-8')
        msg = MIMEMultipart()

        if not message_id:
            if object_id:
                message_id = tools.generate_tracking_message_id(object_id)
            else:
                message_id = make_msgid()
        msg['Message-Id'] = encode_header(message_id)
        if references:
            msg['references'] = encode_header(references)
        msg['Subject'] = encode_header(subject)
        msg['From'] = encode_rfc2822_address_header(email_from)
        del msg['Reply-To']
        if reply_to:
            msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
        else:
            msg['Reply-To'] = msg['From']
        msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
        if email_cc:
            msg['Cc'] = encode_rfc2822_address_header(COMMASPACE.join(email_cc))
        if email_bcc:
            msg['Bcc'] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc))
        msg['Date'] = formatdate()
        # Custom headers may override normal headers or provide additional ones
        for key, value in headers.items():
            msg[pycompat.to_native(ustr(key))] = encode_header(value)

        if subtype == 'html' and not body_alternative:
            # Always provide alternative text body ourselves if possible.
            text = html2text.html2text(email_body)
            alternative_part = MIMEMultipart(_subtype="alternative")
            alternative_part.attach(MIMEText(text, _charset='utf-8', _subtype='plain'))
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        elif body_alternative:
            # Include both alternatives, as specified, within a multipart/alternative part
            alternative_part = MIMEMultipart(_subtype="alternative")
            body_alternative_ = ustr(body_alternative)
            alternative_body_part = MIMEText(body_alternative_, _subtype=subtype_alternative, _charset='utf-8')
            alternative_part.attach(alternative_body_part)
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        else:
            msg.attach(email_text_part)

        if attachments:
            for (fname, fcontent, mime) in attachments:
                filename_rfc2047 = encode_header_param(fname)
                if mime and '/' in mime:
                    maintype, subtype = mime.split('/', 1)
                    part = MIMEBase(maintype, subtype)
                else:
                    part = MIMEBase('application', "octet-stream")

                # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
                # so we fix it by using RFC2047 encoding for the filename instead.
                part.set_param('name', filename_rfc2047)
                part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047)

                part.set_payload(fcontent)
                encoders.encode_base64(part)
                msg.attach(part)
        return msg
Example #33
0
def gmail_sendmail(from_address,
                   password,
                   to_addresses,
                   cc_addresses,
                   bcc_addresses,
                   subject,
                   text_body='',
                   xhtml_body=None,
                   attachments=None):
    gmail_account = from_address
    if attachments == None:
        attachments = []
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gmail_account, password)
    outer = MIMEMultipart('mixed')
    outer['Subject'] = subject
    outer['To'] = ', '.join(to_addresses)
    if cc_addresses is not None:
        outer['Cc'] = ', '.join(cc_addresses)
    else:
        cc_addresses = []
    if bcc_addresses is None:
        bcc_addresses = []
    outer['From'] = from_address

    for att in attachments:
        if sys.platform == 'win32':
            if att[1] != ':':
                # relative path
                path = os.path.join(os.getcwd(), att)
            else:
                path = att
        elif sys.platform.startswith('linux') or \
                sys.platform in ('darwin', 'cygwin'):
            if att[0] != '/':
                # relative path
                path = os.path.join(os.getcwd(), att)
            else:
                path = att
        else:
            raise ValueError('what os is it?!')
        # 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, 'rb')
            # 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=os.path.basename(path))
        outer.attach(msg)

    if xhtml_body is not None:
        html_content = MIMEText(xhtml_body, 'html')
        outer.attach(html_content)
    else:
        text_content = MIMEText(text_body, 'plain')
        outer.attach(text_content)

    server.sendmail(gmail_account, to_addresses + cc_addresses + bcc_addresses,
                    outer.as_string())
    server.close()
Example #34
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            username=dict(type='str'),
            password=dict(type='str', no_log=True),
            host=dict(type='str', default='localhost'),
            port=dict(type='int', default=25),
            sender=dict(type='str', default='root', aliases=['from']),
            to=dict(type='list', default=['root'], aliases=['recipients']),
            cc=dict(type='list', default=[]),
            bcc=dict(type='list', default=[]),
            subject=dict(type='str', required=True, aliases=['msg']),
            body=dict(type='str'),
            attach=dict(type='list', default=[]),
            headers=dict(type='list', default=[]),
            charset=dict(type='str', default='utf-8'),
            subtype=dict(type='str',
                         default='plain',
                         choices=['html', 'plain']),
            secure=dict(type='str',
                        default='try',
                        choices=['always', 'never', 'starttls', 'try']),
            timeout=dict(type='int', default=20),
        ),
        required_together=[['password', 'username']],
    )

    username = module.params.get('username')
    password = module.params.get('password')
    host = module.params.get('host')
    port = module.params.get('port')
    sender = module.params.get('sender')
    recipients = module.params.get('to')
    copies = module.params.get('cc')
    blindcopies = module.params.get('bcc')
    subject = module.params.get('subject')
    body = module.params.get('body')
    attach_files = module.params.get('attach')
    headers = module.params.get('headers')
    charset = module.params.get('charset')
    subtype = module.params.get('subtype')
    secure = module.params.get('secure')
    timeout = module.params.get('timeout')

    code = 0
    secure_state = False
    sender_phrase, sender_addr = parseaddr(sender)

    if not body:
        body = subject

    try:
        if secure != 'never':
            try:
                if PY3:
                    smtp = smtplib.SMTP_SSL(host=host,
                                            port=port,
                                            timeout=timeout)
                else:
                    smtp = smtplib.SMTP_SSL(timeout=timeout)
                code, smtpmessage = smtp.connect(host, port)
                secure_state = True
            except ssl.SSLError as e:
                if secure == 'always':
                    module.fail_json(
                        rc=1,
                        msg='Unable to start an encrypted session to %s:%s: %s'
                        % (host, port, to_native(e)),
                        exception=traceback.format_exc())
            except Exception:
                pass

        if not secure_state:
            if PY3:
                smtp = smtplib.SMTP(host=host, port=port, timeout=timeout)
            else:
                smtp = smtplib.SMTP(timeout=timeout)
            code, smtpmessage = smtp.connect(host, port)

    except smtplib.SMTPException as e:
        module.fail_json(rc=1,
                         msg='Unable to Connect %s:%s: %s' %
                         (host, port, to_native(e)),
                         exception=traceback.format_exc())

    try:
        smtp.ehlo()
    except smtplib.SMTPException as e:
        module.fail_json(rc=1,
                         msg='Helo failed for host %s:%s: %s' %
                         (host, port, to_native(e)),
                         exception=traceback.format_exc())

    if int(code) > 0:
        if not secure_state and secure in ('starttls', 'try'):
            if smtp.has_extn('STARTTLS'):
                try:
                    smtp.starttls()
                    secure_state = True
                except smtplib.SMTPException as e:
                    module.fail_json(
                        rc=1,
                        msg='Unable to start an encrypted session to %s:%s: %s'
                        % (host, port, to_native(e)),
                        exception=traceback.format_exc())
                try:
                    smtp.ehlo()
                except smtplib.SMTPException as e:
                    module.fail_json(rc=1,
                                     msg='Helo failed for host %s:%s: %s' %
                                     (host, port, to_native(e)),
                                     exception=traceback.format_exc())
            else:
                if secure == 'starttls':
                    module.fail_json(
                        rc=1,
                        msg='StartTLS is not offered on server %s:%s' %
                        (host, port))

    if username and password:
        if smtp.has_extn('AUTH'):
            try:
                smtp.login(username, password)
            except smtplib.SMTPAuthenticationError:
                module.fail_json(
                    rc=1,
                    msg=
                    'Authentication to %s:%s failed, please check your username and/or password'
                    % (host, port))
            except smtplib.SMTPException:
                module.fail_json(
                    rc=1,
                    msg='No Suitable authentication method was found on %s:%s'
                    % (host, port))
        else:
            module.fail_json(rc=1,
                             msg="No Authentication on the server at %s:%s" %
                             (host, port))

    if not secure_state and (username and password):
        module.warn('Username and Password was sent without encryption')

    msg = MIMEMultipart(_charset=charset)
    msg['From'] = formataddr((sender_phrase, sender_addr))
    msg['Subject'] = Header(subject, charset)
    msg.preamble = "Multipart message"

    for header in headers:
        # NOTE: Backward compatible with old syntax using '|' as delimiter
        for hdr in [x.strip() for x in header.split('|')]:
            try:
                h_key, h_val = hdr.split('=')
                h_val = to_native(Header(h_val, charset))
                msg.add_header(h_key, h_val)
            except Exception:
                module.warn("Skipping header '%s', unable to parse" % hdr)

    if 'X-Mailer' not in msg:
        msg.add_header('X-Mailer', 'Ansible mail module')

    addr_list = []
    for addr in [x.strip() for x in blindcopies]:
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase

    to_list = []
    for addr in [x.strip() for x in recipients]:
        to_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    msg['To'] = ", ".join(to_list)

    cc_list = []
    for addr in [x.strip() for x in copies]:
        cc_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    msg['Cc'] = ", ".join(cc_list)

    part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset)
    msg.attach(part)

    # NOTE: Backware compatibility with old syntax using space as delimiter is not retained
    #       This breaks files with spaces in it :-(
    for filename in attach_files:
        try:
            part = MIMEBase('application', 'octet-stream')
            with open(filename, 'rb') as fp:
                part.set_payload(fp.read())
            encoders.encode_base64(part)
            part.add_header('Content-disposition',
                            'attachment',
                            filename=os.path.basename(filename))
            msg.attach(part)
        except Exception as e:
            module.fail_json(
                rc=1,
                msg="Failed to send mail: can't attach file %s: %s" %
                (filename, to_native(e)),
                exception=traceback.format_exc())

    composed = msg.as_string()

    try:
        result = smtp.sendmail(sender_addr, set(addr_list), composed)
    except Exception as e:
        module.fail_json(rc=1,
                         msg="Failed to send mail to '%s': %s" %
                         (", ".join(set(addr_list)), to_native(e)),
                         exception=traceback.format_exc())

    smtp.quit()

    if result:
        for key in result:
            module.warn("Failed to send mail to '%s': %s %s" %
                        (key, result[key][0], result[key][1]))
        module.exit_json(msg='Failed to send mail to at least one recipient',
                         result=result)

    module.exit_json(msg='Mail sent successfully', result=result)
Example #35
0
html = '<html><head></head><body><p>' + text + '</p></body></html>'

filepath = "Report_NikonenkoTM.pdf"
basename = os.path.basename(filepath)
filesize = os.path.getsize(filepath)

msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = 'Nikonenko Tatiana <' + sender + '>'
msg['To'] = ', '.join(recipients)
msg['Reply-To'] = sender
msg['Return-Path'] = sender
msg['X-Mailer'] = 'Python/' + (python_version())

part_text = MIMEText(text, 'plain')
part_html = MIMEText(html, 'html')
part_file = MIMEBase('application', 'octet-stream; name="{}"'.format(basename))
part_file.set_payload(open(filepath, "rb").read())
part_file.add_header('Content-Description', basename)
part_file.add_header('Content-Disposition', 'attachment; filename="{}"; size={}'.format(basename, filesize))
encoders.encode_base64(part_file)

msg.attach(part_text)
msg.attach(part_html)
msg.attach(part_file)

mail = smtplib.SMTP_SSL(server)
mail.login(user, password)
mail.sendmail(sender, recipients, msg.as_string())
mail.quit()
Example #36
0
def get_mime_object(is_marked_up, content_string, encoding):
    content_object = {
        "mime_object": None,
        "encoding": None,
        "main_type": None,
        "sub_type": None,
        "is_marked_up": is_marked_up,
    }
    try:
        content_name = os.path.basename(str(content_string))
    except UnicodeEncodeError:
        content_name = os.path.basename(content_string)
    # pylint: disable=unidiomatic-typecheck
    is_raw = type(content_string) == raw
    try:
        is_file = os.path.isfile(content_string)
    except ValueError:
        is_file = False
        content_name = str(abs(hash(content_string)))
    if not is_raw and is_file:
        with open(content_string, "rb") as f:
            content_object["encoding"] = "base64"
            content = f.read()
    else:
        content_object["main_type"] = "text"

        if is_raw:
            content_object["mime_object"] = MIMEText(content_string,
                                                     _charset=encoding)
        else:
            content_object["mime_object"] = MIMEText(content_string,
                                                     "html",
                                                     _charset=encoding)
            content_object["sub_type"] = "html"

        if content_object["sub_type"] is None:
            content_object["sub_type"] = "plain"
        return content_object

    if content_object["main_type"] is None:
        content_type, _ = mimetypes.guess_type(content_string)

        if content_type is not None:
            content_object["main_type"], content_object[
                "sub_type"] = content_type.split("/")

    if content_object["main_type"] is None or content_object[
            "encoding"] is not None:
        if content_object["encoding"] != "base64":
            content_object["main_type"] = "application"
            content_object["sub_type"] = "octet-stream"

    name = (encoding, '', content_name
            ) if not content_object["main_type"] == 'image' else content_name
    mime_object = MIMEBase(content_object["main_type"],
                           content_object["sub_type"],
                           name=name)
    mime_object.set_payload(content)
    if content_object["main_type"] == "application":
        mime_object.add_header('Content-Disposition',
                               'attachment',
                               filename=content_name)
    content_object["mime_object"] = mime_object
    return content_object
Example #37
0
    def TransformOutgoing(self, sender, rcpts, msg, **kwargs):
        # *** msg is email.mime.multipart.MIMEMultipart
        matched = False
        gnupg = None
        sender_keyid = None

        # Prefer to just get everything from the profile VCard, in the
        # common case...
        profile = self._get_sender_profile(sender, kwargs)
        if profile['vcard'] is not None:
            sender_keyid = profile['vcard'].pgp_key
        crypto_format = profile.get('crypto_format') or 'none'

        # Parse the openpgp_header data from the crypto_format
        openpgp_header = [
            p.split(':')[-1] for p in crypto_format.split('+')
            if p.startswith('openpgp_header:')
        ]
        if not openpgp_header:
            openpgp_header = self.config.prefs.openpgp_header and ['CFG']

        if openpgp_header[0] != 'N' and not sender_keyid:
            # This is a fallback: this shouldn't happen much in normal use
            try:
                gnupg = gnupg or GnuPG(self.config, event=GetThreadEvent())
                seckeys = dict([
                    (uid["email"], fp)
                    for fp, key in gnupg.list_secret_keys().iteritems()
                    if key["capabilities_map"].get("encrypt")
                    and key["capabilities_map"].get("sign")
                    for uid in key["uids"]
                ])
                sender_keyid = seckeys.get(sender)
            except (KeyError, TypeError, IndexError, ValueError):
                traceback.print_exc()

        if sender_keyid and openpgp_header:
            preference = {
                'ES': 'signencrypt',
                'SE': 'signencrypt',
                'E': 'encrypt',
                'S': 'sign',
                'N': 'unprotected',
                'CFG': self.config.prefs.openpgp_header
            }[openpgp_header[0].upper()]
            msg["OpenPGP"] = ("id=%s; preference=%s" %
                              (sender_keyid, preference))

        if ('attach-pgp-pubkey' in msg
                and msg['attach-pgp-pubkey'][:3].lower() in ('yes', 'tru')):
            gnupg = gnupg or GnuPG(self.config, event=GetThreadEvent())
            if sender_keyid:
                keys = gnupg.list_keys(selectors=[sender_keyid])
            else:
                keys = gnupg.address_to_keys(
                    AddressHeaderParser(sender).addresses_list()[0])

            key_count = 0
            for fp, key in keys.iteritems():
                if not any(key["capabilities_map"].values()):
                    continue
                # We should never really hit this more than once. But if we
                # do, should still be fine.
                keyid = key["keyid"]
                data = gnupg.get_pubkey(keyid)

                try:
                    from_name = key["uids"][0]["name"]
                    filename = _('Encryption key for %s') % from_name
                except:
                    filename = _('My encryption key')

                if self.config.prefs.gpg_html_wrap:
                    data = self._wrap_key_in_html(filename, data)
                    ext = 'html'
                else:
                    ext = 'asc'

                att = MIMEBase('application', 'pgp-keys')
                att.set_payload(data)
                encoders.encode_base64(att)
                del att['MIME-Version']
                att.add_header('Content-Id', MakeContentID())
                att.add_header('Content-Disposition',
                               'attachment',
                               filename=filename + '.' + ext)
                att.signature_info = SignatureInfo(parent=msg.signature_info)
                att.encryption_info = EncryptionInfo(
                    parent=msg.encryption_info)
                msg.attach(att)
                key_count += 1

            if key_count > 0:
                msg['x-mp-internal-pubkeys-attached'] = "Yes"

        return sender, rcpts, msg, matched, True
Example #38
0
     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)  # attachment para adjuntos regulares, inline para imágenes en el cuerpo del correo
     msg.add_header('Content-ID', '<'+filename+'>')  # Necesario para referenciar imágenes desde el cuerpo del correo
     outer.attach(msg)
 # Now send or store the message
 composed = outer.as_string()
 
 # Listo. Composed contiene el mensaje armado completo, como un string, listo para ser enviado.
 server = smtplib.SMTP(config['servidor_smtp'], timeout=config['timeout'])
 server.starttls()
 server.login(config['username'], config['password'])
Example #39
0
def reply_mail_func(
    username,
    password,
    receiver_email="",
    Subject="",
    message="",
    list_file=[],
    crypto_type=None,
):
    port = 587
    smtp_server = "smtp.gmail.com"

    # Neu khong co nguoi nhan
    if receiver_email != "":

        # Neu message khong rong hoac co file dinh kem
        if message != "" or list_file[0] != "":
            bbc = receiver_email
            msg = MIMEMultipart()

            # msg = MIMEMultipart("alternative"); #Dùng khi gửi theo dạng html

            # Thông tin về From, To, Subject, Bcc của mail.
            msg["From"] = username
            msg["To"] = receiver_email
            msg["Subject"] = Subject
            msg["Bcc"] = bbc

            print("send mail")

            # Neu message khong rong
            if message != "":
                # Message của người gửi muốn người nhận nhận được
                body_mail = message

                # Định dạng message của mail theo kiểu plain text và lưu vào message_mail
                message_mail = MIMEText(body_mail, "plain", "utf-8")
                # part2 = MIMEText(html, "html")

                # Đính kèm nội dung mail đang được lưu trong par1 vào msg
                msg.attach(message_mail)

            # Neu co file dinh kem
            if list_file[0] != "":
                attachments = list_file  # In same directory as script
                # sau khi print ra thì filepath bị split mỗi kí tự thành 1 phần tử của list => sai
                # cần fix lỗi chỗ này.

                for i in range(0, len(attachments)):
                    file = attachments[i]
                    file_basename = os.path.basename(file)
                    # Open PDF file in binary mode
                    with open(file, "rb") as attachment:
                        # Add file as application/octet-stream
                        # Email client can usually download this automatically as attachment
                        file_mail = MIMEBase("application", "octet-stream")
                        file_mail.set_payload(attachment.read())

                    # Encode file in ASCII characters to send by email
                    encoders.encode_base64(file_mail)

                    # Add header as key/value pair to attachment part
                    file_mail.add_header(
                        "Content-Disposition",
                        "attachment",
                        filename=("utf-8", "", file_basename),
                    )
                    msg.attach(file_mail)

            all_message = msg.as_string()

            try:
                # Tạo một đối tượng SMTP, cho phép kết nối tới server của SMTP và cho phép sử dụng các phương thức của SMTP
                server = smtplib.SMTP(smtp_server, port)

                # Tạo kết nối SMTP không bảo mật và mã hóa nó với starttls()
                server.starttls()

                # Đăng nhập tài khoản gmail của người gửi
                server.login(username, password)

                # Tiến hành gửi mail từ người gửi tới người nhận, message được định dang theo string.
                server.sendmail(username, receiver_email, all_message)

                # Trong trường hợp có lỗi khi kết nối tới server của SMTP hoặc xảy ra bất kì lỗi gì trong quá trình xử lí
                # Sẽ xuất thông báo lỗi
            except Exception as e:

                print(e)

            finally:
                messagebox.showinfo("Success", "Sent!")
                server.quit()

        # Khong co message va file
        else:
            messagebox.showerror("Error", "The content is empty!")

    # Khong co nguoi nhan
    else:
        messagebox.showerror("Error", "Please specify at least one recipient.!")
Example #40
0
    def submit(self, form, *args):

        data = form.data
        model = form.model

        if isinstance(self.send_to, (list, tuple)):
            self.send_to = COMMASPACE.join(self.send_to)

        msg = MIMEMultipart()

        # Special treatment for from... Check if it refers to a form field
        #
        if re.match("\$\{.+\}", self.send_from):
            try:
                var = re.match("\$\{(.+)\}", self.send_from).groups()[0]
                self.send_from = form.getFieldValue(var)
            except:
                pass

        # Special treatment for reply_to... Check if it refers to a form field
        #
        if re.match("\$\{.+\}", self.reply_to):
            try:
                var = re.match("\$\{(.+)\}", self.reply_to).groups()[0]
                self.reply_to = form.getFieldValue(var)
            except:
                pass

        msg['From'] = self.send_from
        msg['To'] = self.send_to
        if hasattr(self, 'reply_to') and self.reply_to:
            msg['Reply-To'] = self.reply_to
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = self.subject

        text = [getattr(self, 'pre_text', "")]
        files = []

        for field in data.getFields():

            if not self.isFile(field, model):

                text.append("%s: %s" %
                            (field,
                             form.getFieldValue(
                                 field, default=data[field], lexical=True)))

            else:

                files.append(data[field])

        text.append(getattr(self, 'post_text', ""))

        msg.attach(MIMEText("\n".join(text)))

        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(f)
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % "pipo.txt")
            msg.attach(part)

        smtp = smtplib.SMTP(getattr(self, 'host', "localhost"),
                            getattr(self, 'port', "25"))

        if hasattr(self, 'tls'):
            smtp.starttls()

        if hasattr(self, 'user'):
            smtp.login(self.user, getattr(self, 'pwd', ''))

        smtp.sendmail(self.send_from, self.send_to, msg.as_string())
        smtp.close()
Example #41
0
'''

address = ""  # [email protected]
password = ""  # password

msg = MIMEMultipart()
msg["Subject"] = "Results from " + str(os.uname()[1])
msg["From"] = address
msg["To"] = address

text = MIMEText(\
"Sysname = " +str(os.uname()[0])+'\n' +\
"Hostname = "+str(os.uname()[1])+'\n' +\
"Release = " +str(os.uname()[2])+'\n' +\
"Version = " +str(os.uname()[3])+'\n' +\
"Machine = " +str(os.uname()[4])+'\n'  )

part = MIMEBase("application", "octet-stream")
part.set_payload(open(filename, 'rb').read())
encoders.encode_base64(part)
part.add_header("Content-Disposition",
                "attachment; filename=%s" % os.path.basename(filename))

msg.attach(text)
msg.attach(part)

smtp = SMTP_SSL()
smtp.connect("smtp.yandex.ru")
smtp.login(address, password)
smtp.sendmail(address, address, msg.as_string())
smtp.quit()
for i in range(0, len(renewaldatelist)):
    if renewaldatelist[i] <= 1:
        notificationNeeded = True
        break

with open(os.path.join(save_path, 'RenewalCalculator.txt'), 'w') as file1:
    for row in listItems:  # for loop to add data into the text file
        file1.write(' || '.join([str(a) for a in row]) + '\n')

if (notificationNeeded):
    print(
        'Your list contains a product which has either expired or going to expire soon'
    )
    with open(file1.name, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())

    encoders.encode_base64(part)

    part.add_header(
        "Content-Disposition",
        "attachment; filename= RenewalCalculator.txt",
    )

    message.attach(part)
    text = message.as_string()

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
def home(request):
    msg1="Instructions:  Please upload both the files and then click on Reconcile"


    if request.method == 'POST' and request.FILES['myfile'] and request.FILES['myfile1']:
        excel = request.FILES['myfile']
        excl = request.FILES['myfile1']
        df1 = pd.read_csv(excel, error_bad_lines=False, encoding='utf-8')
        df2 = pd.read_csv(excl, error_bad_lines=False, encoding='utf-8')

        df1.columns = ['gstin', 'invoice_date', 'customer_name', 'invoiceno', 'ctinno', 'taxablevalue', 'cgst', 'sgst',
                       'igst']
        df2.columns = ['gstin','period','ctinno','customer_name','counter_filing_status','invoiceno','invoice_value',
                       'invoice_date','placeofsupply','invoicetype'
                       ,'reversecharge','num','rate','taxablevalue','igst','cgst','sgst','cess']

        df1['invoice_date'] = pd.to_datetime(df1['invoice_date'])
        df2['invoice_date'] = pd.to_datetime(df2['invoice_date'])

        df1.loc[df1['invoice_date'].between('2017-04-01', '2018-03-31', inclusive=True), 'FY'] = '2017-18'
        df1.loc[df1['invoice_date'].between('2018-04-01', '2019-03-31', inclusive=True), 'FY'] = '2018-19'
        df1.loc[df1['invoice_date'].between('2019-04-01', '2020-03-31', inclusive=True), 'FY'] = '2019-20'
        df1.loc[df1['invoice_date'].between('2020-04-01', '2021-03-31', inclusive=True), 'FY'] = '2020-21'

        df2.loc[df2['invoice_date'].between('2017-04-01', '2018-03-31', inclusive=True), 'FY'] = '2017-18'
        df2.loc[df2['invoice_date'].between('2018-04-01', '2019-03-31', inclusive=True), 'FY'] = '2018-19'
        df2.loc[df2['invoice_date'].between('2019-04-01', '2020-03-31', inclusive=True), 'FY'] = '2019-20'
        df2.loc[df2['invoice_date'].between('2020-04-01', '2021-03-31', inclusive=True), 'FY'] = '2020-21'

        df1.fillna(0, inplace=True)
        df2.fillna(0, inplace=True)

        df1.taxablevalue = df1.taxablevalue.round(decimals=0).astype('int64')
        df2.taxablevalue = df2.taxablevalue.round(decimals=0).astype('int64')

        df1["length"] = (df1['ctinno'].str.len() == 15)
        df2["length"] = (df2['ctinno'].str.len() == 15)

        df1['totaltax'] = df1['cgst'] + df1['sgst'] + df1['igst']
        df2['totaltax'] = df2['cgst'] + df2['sgst'] + df2['igst']

        df1["Concat"]= df1["ctinno"].map(str)+df1["invoiceno"].map(str)+df1["FY"].map(str)+df1["taxablevalue"].map(str)+df1["totaltax"].map(str)
        df2["Concat"]= df2["ctinno"].map(str)+df2["invoiceno"].map(str)+df2["FY"].map(str)+df2["taxablevalue"].map(str)+df2["totaltax"].map(str)+df2["rate"].map(str)

        df1["dup_remove"] = df1.groupby(['Concat']).cumcount()+1
        df2["dup_remove"] = df2.groupby(['Concat']).cumcount()+1

        df1.loc[(df1['dup_remove']>1) ,'Dup_Remarks'] = 'Duplicate_Invoice'
        df2.loc[(df2['dup_remove']>1) ,'Dup_Remarks'] = 'Duplicate_Invoice'

        df1.loc[(df1['dup_remove']>1) ,'totaltax'] = 0
        df2.loc[(df2['dup_remove']>1) ,'totaltax'] = 0

        df1.loc[(df1['totaltax']<0) ,'totaltax'] = 0
        df2.loc[(df2['totaltax']<0) ,'totaltax'] = 0

        df1.loc[(df1['invoiceno']==0) ,'totaltax'] = 0
        df2.loc[(df2['invoiceno']==0) ,'totaltax'] = 0

        df1.totaltax = df1.totaltax.round(decimals=0).astype('int64')
        df2.totaltax = df2.totaltax.round(decimals=0).astype('int64')

        df1["ConcatColumn"] = df1["ctinno"].map(str) + df1["invoiceno"].map(str)
        df2["ConcatColumn"] = df2["ctinno"].map(str) + df2["invoiceno"].map(str)

        df1["ConcatColumn1"] = df1.groupby(['ConcatColumn'])['totaltax'].transform('sum')
        df2["ConcatColumn1"] = df2.groupby(['ConcatColumn'])['totaltax'].transform('sum')

        df1["dup_number"] = df1.groupby(['ConcatColumn']).cumcount() + 1
        df2["dup_number"] = df2.groupby(['ConcatColumn']).cumcount() + 1

        df1["ConcatColumn_dup"] = df1["dup_number"].map(str) + df1["ConcatColumn"].map(str)
        df2["ConcatColumn_dup"] = df2["dup_number"].map(str) + df2["ConcatColumn"].map(str)

        New_one = pd.merge(left=df1, right=df2[['ConcatColumn_dup', 'ConcatColumn1']], left_on='ConcatColumn_dup',
                           right_on='ConcatColumn_dup', how='left')
        New_two = pd.merge(left=df2, right=df1[['ConcatColumn_dup', 'ConcatColumn1']], left_on='ConcatColumn_dup',
                           right_on='ConcatColumn_dup', how='left')

        New_one['Flag'] = False
        New_one.loc[New_one.ConcatColumn_dup.isin(
            New_two.drop_duplicates(subset=['ConcatColumn_dup']).ConcatColumn_dup.values), 'Flag'] = True

        New_two['Flag'] = False
        New_two.loc[New_two.ConcatColumn_dup.isin(
            New_one.drop_duplicates(subset=['ConcatColumn_dup']).ConcatColumn_dup.values), 'Flag'] = True

        New_one["ConcatColumn1a"] = New_one.groupby(['ConcatColumn'])['ConcatColumn1_y'].transform('sum')
        New_two["ConcatColumn1a"] = New_two.groupby(['ConcatColumn'])['ConcatColumn1_y'].transform('sum')

        New_one.loc[New_one['ConcatColumn1_y'].isnull(), 'ConcatColumn1_y'] = New_one['ConcatColumn1a']
        New_two.loc[New_two['ConcatColumn1_y'].isnull(), 'ConcatColumn1_y'] = New_two['ConcatColumn1a']

        New_one['Diff1'] = New_one['ConcatColumn1_x'] - New_one['ConcatColumn1_y']
        New_two['Diff1'] = New_two['ConcatColumn1_x'] - New_two['ConcatColumn1_y']

        New_one['Remarks1'] = False
        New_one.loc[New_one['Diff1'].between(-10.00, 10.00, inclusive=True) & (New_one['dup_remove'] == 1) & (
                    New_one['ConcatColumn1_y'] != 0), 'Remarks1'] = True
        New_two['Remarks1'] = False
        New_two.loc[New_two['Diff1'].between(-10.00, 10.00, inclusive=True) & (New_two['dup_remove'] == 1) & (
                    New_two['ConcatColumn1_y'] != 0), 'Remarks1'] = True
##Level 1 comlpeted ##

        ###### Stage 2 validation - Modified Invoice

        New_one['invoiceno_New'] = New_one['invoiceno'].replace(
            [" ", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
             'u', 'v', 'w', 'x', 'y', 'z',
             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
             'V', 'W', 'X', 'Y', 'Z',
             '2017-18', '2017-2018', '2018-19', '2018-2019', '/1718', '/1819', '/17-18', '17-18/', '17-18',
             '18-19', '/17 ', '/18 ', '/2017', '/2018', '/2019', '-', '/', '&', " "], '', regex=True)
        New_one['invoiceno_New1'] = New_one.invoiceno_New.str.lstrip("0")
        New_one["invoiceno_New1"].fillna(New_one.invoiceno_New, inplace=True)
        New_two['invoiceno_New'] = New_two['invoiceno'].replace(
            [" ", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
             'u', 'v', 'w', 'x', 'y', 'z',
             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
             'V', 'W', 'X', 'Y', 'Z',
             '2017-18', '2017-2018', '2018-19', '2018-2019', '/1718', '/1819', '/17-18', '17-18/', '17-18',
             '18-19', '/17 ', '/18 ', '/2017', '/2018', '/2019', '-', '/', '&', " "], '', regex=True)
        New_two['invoiceno_New1'] = New_two.invoiceno_New.str.lstrip("0")
        New_two["invoiceno_New1"].fillna(New_two.invoiceno_New, inplace=True)

        New_one["Concat1"] = New_one["ctinno"].map(str) + New_one["invoiceno_New1"].map(str) + New_one["FY"].map(str) + \
                             New_one["taxablevalue"].map(str) + New_one["totaltax"].map(str)
        New_two["Concat1"] = New_two["ctinno"].map(str) + New_two["invoiceno_New1"].map(str) + New_two["FY"].map(str) + \
                             New_two["taxablevalue"].map(str) + New_two["totaltax"].map(str) + New_two["rate"].map(str)

        New_one["dup_remove1"] = New_one.groupby(['Concat1']).cumcount() + 1
        New_two["dup_remove1"] = New_two.groupby(['Concat1']).cumcount() + 1

        New_one.loc[(New_one['dup_remove1'] > 1), 'Dup_Remarks'] = 'Duplicate_Invoice'
        New_two.loc[(New_two['dup_remove1'] > 1), 'Dup_Remarks'] = 'Duplicate_Invoice'

        New_one.loc[(New_one['dup_remove1'] > 1), 'totaltax'] = 0
        New_two.loc[(New_two['dup_remove1'] > 1), 'totaltax'] = 0

        New_one["ConcatColumn2"] = New_one["ctinno"].map(str) + New_one["invoiceno_New1"].map(str) + New_one["FY"].map(
            str)
        New_two["ConcatColumn2"] = New_two["ctinno"].map(str) + New_two["invoiceno_New1"].map(str) + New_one["FY"].map(
            str)

        New_one["ConcatColumn2a"] = New_one.groupby(['ConcatColumn2'])['totaltax'].transform('sum')
        New_two["ConcatColumn2a"] = New_two.groupby(['ConcatColumn2'])['totaltax'].transform('sum')

        New_one["dup_number2"] = New_one.groupby(['ConcatColumn2']).cumcount() + 1
        New_two["dup_number2"] = New_two.groupby(['ConcatColumn2']).cumcount() + 1

        New_one["ConcatColumn_dup2"] = New_one["dup_number2"].map(str) + New_one["ConcatColumn2"].map(str)
        New_two["ConcatColumn_dup2"] = New_two["dup_number2"].map(str) + New_two["ConcatColumn2"].map(str)

        New_3 = pd.merge(left=New_one, right=New_two[['ConcatColumn_dup2', 'ConcatColumn2a']],
                         left_on='ConcatColumn_dup2', right_on='ConcatColumn_dup2', how='left')
        New_4 = pd.merge(left=New_two, right=New_one[['ConcatColumn_dup2', 'ConcatColumn2a']],
                         left_on='ConcatColumn_dup2', right_on='ConcatColumn_dup2', how='left')

        New_3['Flag2'] = False
        New_3.loc[New_3.ConcatColumn_dup2.isin(
            New_4.drop_duplicates(subset=['ConcatColumn_dup2']).ConcatColumn_dup2.values), 'Flag2'] = True

        New_4['Flag2'] = False
        New_4.loc[New_4.ConcatColumn_dup2.isin(
            New_3.drop_duplicates(subset=['ConcatColumn_dup2']).ConcatColumn_dup2.values), 'Flag2'] = True

        New_3["ConcatColumn2a1"] = New_3.groupby(['ConcatColumn2'])['ConcatColumn2a_y'].transform('sum')
        New_4["ConcatColumn2a1"] = New_4.groupby(['ConcatColumn2'])['ConcatColumn2a_y'].transform('sum')

        New_3.loc[New_3['ConcatColumn2a_y'].isnull(), 'ConcatColumn2a_y'] = New_3['ConcatColumn2a1']
        New_4.loc[New_4['ConcatColumn2a_y'].isnull(), 'ConcatColumn2a_y'] = New_4['ConcatColumn2a1']

        New_3['Diff2'] = New_3['ConcatColumn2a_x'] - New_3['ConcatColumn2a_y']
        New_4['Diff2'] = New_4['ConcatColumn2a_x'] - New_4['ConcatColumn2a_y']

        New_3['Remarks2'] = False
        New_3.loc[New_3['Diff2'].between(-10.00, 10.00, inclusive=True) & (New_3['dup_remove1'] == 1) & (
                    New_3['ConcatColumn2a_y'] != 0), 'Remarks2'] = True
        New_4['Remarks2'] = False
        New_4.loc[New_4['Diff2'].between(-10.00, 10.00, inclusive=True) & (New_4['dup_remove1'] == 1) & (
                    New_4['ConcatColumn2a_y'] != 0), 'Remarks2'] = True
        ###### Stage 3 Validation - taxablevalue

        New_3["ConcatColumn3"] = New_3["ctinno"].map(str) + New_3["taxablevalue"].map(str) + New_3["FY"].map(str)
        New_4["ConcatColumn3"] = New_4["ctinno"].map(str) + New_4["taxablevalue"].map(str) + New_4["FY"].map(str)

        New_3.loc[(New_3['Remarks1'] == False) & (New_3['Remarks2'] == False), 'ConcatColumn3a'] = \
        New_3.groupby(['ConcatColumn3'])['totaltax'].transform('sum')
        New_4.loc[(New_4['Remarks1'] == False) & (New_4['Remarks2'] == False), 'ConcatColumn3a'] = \
        New_4.groupby(['ConcatColumn3'])['totaltax'].transform('sum')

        New_3["dup_number3"] = New_3.groupby(['ConcatColumn3']).cumcount() + 1
        New_4["dup_number3"] = New_4.groupby(['ConcatColumn3']).cumcount() + 1

        New_3["ConcatColumn_dup3"] = New_3["dup_number3"].map(str) + New_3["ConcatColumn3"].map(str)
        New_4["ConcatColumn_dup3"] = New_4["dup_number3"].map(str) + New_4["ConcatColumn3"].map(str)

        New_5 = pd.merge(left=New_3, right=New_4[['ConcatColumn_dup3', 'ConcatColumn3a']], left_on='ConcatColumn_dup3',
                         right_on='ConcatColumn_dup3', how='left')
        New_6 = pd.merge(left=New_4, right=New_3[['ConcatColumn_dup3', 'ConcatColumn3a']], left_on='ConcatColumn_dup3',
                         right_on='ConcatColumn_dup3', how='left')

        New_5['Flag3'] = False
        New_5.loc[New_5.ConcatColumn_dup3.isin(
            New_6.drop_duplicates(subset=['ConcatColumn_dup3']).ConcatColumn_dup3.values), 'Flag3'] = True

        New_6['Flag3'] = False
        New_6.loc[New_6.ConcatColumn_dup3.isin(
            New_5.drop_duplicates(subset=['ConcatColumn_dup3']).ConcatColumn_dup3.values), 'Flag3'] = True

        New_5["ConcatColumn3a1"] = New_5.groupby(['ConcatColumn3'])['ConcatColumn3a_y'].transform('mean')
        New_6["ConcatColumn3a1"] = New_6.groupby(['ConcatColumn3'])['ConcatColumn3a_y'].transform('mean')

        New_5.loc[New_5['ConcatColumn3a_y'].isnull(), 'ConcatColumn3a_y'] = New_5['ConcatColumn3a1']
        New_6.loc[New_6['ConcatColumn3a_y'].isnull(), 'ConcatColumn3a_y'] = New_6['ConcatColumn3a1']

        New_5['Diff3'] = New_5['ConcatColumn3a_x'] - New_5['ConcatColumn3a_y']
        New_6['Diff3'] = New_6['ConcatColumn3a_x'] - New_6['ConcatColumn3a_y']

        New_5['Remarks3'] = False
        New_5.loc[
            New_5['Diff3'].between(-10.00, 10.00, inclusive=True) & (New_5['ConcatColumn3a_y'] != 0), 'Remarks3'] = True
        New_6['Remarks3'] = False
        New_6.loc[
            New_6['Diff3'].between(-10.00, 10.00, inclusive=True) & (New_6['ConcatColumn3a_y'] != 0), 'Remarks3'] = True
        ###### Stage 4 Validation - GST Only

        New_5["ConcatColumn4"] = New_5["ctinno"].map(str) + New_5["FY"].map(str)
        New_6["ConcatColumn4"] = New_6["ctinno"].map(str) + New_6["FY"].map(str)

        New_5["dup_number4"] = New_5.groupby(['ConcatColumn4']).cumcount() + 1
        New_6["dup_number4"] = New_6.groupby(['ConcatColumn4']).cumcount() + 1

        New_5["ConcatColumn_dup4"] = New_5["dup_number4"].map(str) + New_5["ConcatColumn4"].map(str)
        New_6["ConcatColumn_dup4"] = New_6["dup_number4"].map(str) + New_6["ConcatColumn4"].map(str)

        New_5["ConcatColumn4a"] = New_5.groupby(['ConcatColumn4'])['totaltax'].transform('sum')
        New_6["ConcatColumn4a"] = New_6.groupby(['ConcatColumn4'])['totaltax'].transform('sum')

        New_7 = pd.merge(left=New_5, right=New_6[['ConcatColumn_dup4', 'ConcatColumn4a']], left_on='ConcatColumn_dup4',
                         right_on='ConcatColumn_dup4', how='left')
        New_8 = pd.merge(left=New_6, right=New_5[['ConcatColumn_dup4', 'ConcatColumn4a']], left_on='ConcatColumn_dup4',
                         right_on='ConcatColumn_dup4', how='left')

        New_7['Flag4'] = False
        New_7.loc[New_7.ConcatColumn_dup4.isin(
            New_8.drop_duplicates(subset=['ConcatColumn_dup4']).ConcatColumn_dup4.values), 'Flag4'] = True

        New_8['Flag4'] = False
        New_8.loc[New_8.ConcatColumn_dup4.isin(
            New_7.drop_duplicates(subset=['ConcatColumn_dup4']).ConcatColumn_dup4.values), 'Flag4'] = True

        New_7["ConcatColumn4a1"] = New_7.groupby(['ctinno'])['ConcatColumn4a_y'].transform('mean')
        New_8["ConcatColumn4a1"] = New_8.groupby(['ctinno'])['ConcatColumn4a_y'].transform('mean')

        New_7.loc[New_7['ConcatColumn4a_y'].isnull(), 'ConcatColumn4a_y'] = New_7['ConcatColumn4a1']
        New_8.loc[New_8['ConcatColumn4a_y'].isnull(), 'ConcatColumn4a_y'] = New_8['ConcatColumn4a1']

        New_7['Diff4'] = New_7['ConcatColumn4a_x'] - New_7['ConcatColumn4a_y']
        New_8['Diff4'] = New_8['ConcatColumn4a_x'] - New_8['ConcatColumn4a_y']

        New_7['Remarks4'] = False
        New_7.loc[
            New_7['Diff4'].between(-10.00, 10.00, inclusive=True) & (New_7['ConcatColumn4a_y'] != 0), 'Remarks4'] = True
        New_8['Remarks4'] = False
        New_8.loc[
            New_8['Diff4'].between(-10.00, 10.00, inclusive=True) & (New_8['ConcatColumn4a_y'] != 0), 'Remarks4'] = True

        ###### Stage 5 Validation - GST+ConcatColumn1_x

        New_7["ConcatColumn5"] = New_7["ctinno"].map(str) + New_7["ConcatColumn1_x"].map(str) + New_7["FY"].map(str)
        New_8["ConcatColumn5"] = New_8["ctinno"].map(str) + New_8["ConcatColumn1_x"].map(str) + New_8["FY"].map(str)

        New_7.loc[(New_7['Remarks1'] == False) & (New_7['Remarks2'] == False) & (
                    New_7['Remarks3'] == False), 'ConcatColumn5a'] = New_7.groupby(['ConcatColumn5'])[
            'totaltax'].transform('sum')
        New_8.loc[(New_8['Remarks1'] == False) & (New_8['Remarks2'] == False) & (
                    New_8['Remarks3'] == False), 'ConcatColumn5a'] = New_8.groupby(['ConcatColumn5'])[
            'totaltax'].transform('sum')

        New_7["dup_number5"] = New_7.groupby(['ConcatColumn5']).cumcount() + 1
        New_8["dup_number5"] = New_8.groupby(['ConcatColumn5']).cumcount() + 1

        New_7["ConcatColumn_dup5"] = New_7["dup_number5"].map(str) + New_7["ConcatColumn5"].map(str)
        New_8["ConcatColumn_dup5"] = New_8["dup_number5"].map(str) + New_8["ConcatColumn5"].map(str)

        New_9 = pd.merge(left=New_7, right=New_8[['ConcatColumn_dup5', 'ConcatColumn5a']], left_on='ConcatColumn_dup5',
                         right_on='ConcatColumn_dup5', how='left')
        New_10 = pd.merge(left=New_8, right=New_7[['ConcatColumn_dup5', 'ConcatColumn5a']], left_on='ConcatColumn_dup5',
                          right_on='ConcatColumn_dup5', how='left')

        New_9["Flag5"] = (New_9['ConcatColumn5a_y'] > 0)
        New_10["Flag5"] = (New_10['ConcatColumn5a_y'] > 0)

        New_9["ConcatColumn5a1"] = New_9.groupby(['ConcatColumn5'])['ConcatColumn5a_y'].transform('mean')
        New_10["ConcatColumn5a1"] = New_10.groupby(['ConcatColumn5'])['ConcatColumn5a_y'].transform('mean')

        New_9.loc[New_9['ConcatColumn5a_y'].isnull(), 'ConcatColumn5a_y'] = New_9['ConcatColumn5a1']
        New_10.loc[New_10['ConcatColumn5a_y'].isnull(), 'ConcatColumn5a_y'] = New_10['ConcatColumn5a1']

        New_9['Diff5'] = New_9['ConcatColumn5a_x'] - New_9['ConcatColumn5a_y']
        New_10['Diff5'] = New_10['ConcatColumn5a_x'] - New_10['ConcatColumn5a_y']

        New_9['Remarks5'] = False
        New_9.loc[
            New_9['Diff5'].between(-10.00, 10.00, inclusive=True) & (New_9['ConcatColumn5a_y'] != 0), 'Remarks5'] = True
        New_10['Remarks5'] = False
        New_10.loc[New_10['Diff5'].between(-10.00, 10.00, inclusive=True) & (
                    New_10['ConcatColumn5a_y'] != 0), 'Remarks5'] = True

        ############******************************

        New_9['Datasource'] = 'Invoice'
        New_10['Datasource'] = 'Portal'

        ##### Invoice Remarks Validation

        New_9.loc[(New_9['length'] == False), 'Final_Remarks'] = 'GSTIN_Number_Error'

        New_9.loc[(New_9['length'] == True) & (
                    New_9['Dup_Remarks'] == 'Duplicate_Invoice'), 'Final_Remarks'] = 'Duplicate_Invoice'

        New_9.loc[(New_9['length'] == True) & (New_9['Dup_Remarks'].isnull()) & (
                    New_9['totaltax'] < 0), 'Final_Remarks'] = 'Total_Tax_is_Negative'

        New_9.loc[(New_9['length'] == True) & (New_9['Dup_Remarks'].isnull()) & (
                    New_9['invoiceno'] == 0), 'Final_Remarks'] = 'Invoice_number_Wrong'

        New_9.loc[(New_9['length'] == True) & (New_9['Dup_Remarks'].isnull()) & (
                    New_9['totaltax'] == 0), 'Final_Remarks'] = 'Total_Tax_Value_is_Zero'

        New_9.loc[
            (New_9['Remarks1'] == True) & (New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = '1_Completely_Matched'

        New_9.loc[(New_9['Remarks1'] == False) & (New_9['Remarks2'] == True) & (
            New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = '2_Conditionally_Matched'

        New_9.loc[(New_9['Remarks1'] == False) & (New_9['Remarks2'] == False) & (New_9['Remarks3'] == True) & (
            New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = '3_Taxablevalue_Tax_Matched'

        New_9.loc[(New_9['Remarks1'] == False) & (New_9['Remarks2'] == False) & (New_9['Remarks3'] == False) & (
                    New_9['Remarks5'] == True) & (
                      New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = '4_GSTIN+TotalTaxSum_Tax_Matched'

        New_9.loc[(New_9['Remarks1'] == False) & (New_9['Remarks2'] == False) & (New_9['Remarks3'] == False) & (
                    New_9['Remarks5'] == False) & (New_9['Remarks4'] == True) & (
                      New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = '5_GSTIN_Only_Tax_Matched'

        New_9.loc[(New_9['Final_Remarks'].isnull()) & (New_9['ConcatColumn1_y'] != 0) & (
                    New_9['Diff1'] < 0), 'Final_Remarks'] = 'Excess_Tax_in_Portal'
        New_9.loc[(New_9['Final_Remarks'].isnull()) & (New_9['ConcatColumn1_y'] != 0) & (
                    New_9['Diff1'] > 0), 'Final_Remarks'] = 'Excess_Tax_in_Invoice'

        New_9.loc[(New_9['Final_Remarks'].isnull()) & (New_9['ConcatColumn2a_y'] != 0) & (
                    New_9['Diff2'] < 0), 'Final_Remarks'] = 'Excess_Tax_in_Portal'
        New_9.loc[(New_9['Final_Remarks'].isnull()) & (New_9['ConcatColumn2a_y'] != 0) & (
                    New_9['Diff2'] > 0), 'Final_Remarks'] = 'Excess_Tax_in_Invoice'

        New_9.loc[(New_9['Final_Remarks'].isnull()), 'Final_Remarks'] = 'Available_in_Purchse_register_Not_in_Portal'

        ##### Portal Remarks Validation

        New_10.loc[(New_10['length'] == False), 'Final_Remarks'] = 'GSTIN_Number_Error'

        New_10.loc[(New_10['length'] == True) & (
                    New_10['Dup_Remarks'] == 'Duplicate_Invoice'), 'Final_Remarks'] = 'Duplicate_Invoice'

        New_10.loc[(New_10['length'] == True) & (New_10['Dup_Remarks'].isnull()) & (
                    New_10['totaltax'] < 0), 'Final_Remarks'] = 'Total_Tax_is_Negative'

        New_10.loc[(New_10['length'] == True) & (New_10['Dup_Remarks'].isnull()) & (
                    New_10['invoiceno'] == 0), 'Final_Remarks'] = 'Invoice_number_Wrong'

        New_10.loc[(New_10['length'] == True) & (New_10['Dup_Remarks'].isnull()) & (
                    New_10['totaltax'] == 0), 'Final_Remarks'] = 'Total_Tax_Value_is_Zero'

        New_10.loc[
            (New_10['Remarks1'] == True) & (New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = '1_Completely_Matched'

        New_10.loc[(New_10['Remarks1'] == False) & (New_10['Remarks2'] == True) & (
            New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = '2_Conditionally_Matched'

        New_10.loc[(New_10['Remarks1'] == False) & (New_10['Remarks2'] == False) & (New_10['Remarks3'] == True) & (
            New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = '3_Taxablevalue_Tax_Matched'

        New_10.loc[(New_10['Remarks1'] == False) & (New_10['Remarks2'] == False) & (New_10['Remarks3'] == False) & (
                    New_10['Remarks5'] == True) & (
                       New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = '4_GSTIN+TotalTaxSum_Tax_Matched'

        New_10.loc[(New_10['Remarks1'] == False) & (New_10['Remarks2'] == False) & (New_10['Remarks3'] == False) & (
                    New_10['Remarks5'] == False) & (New_10['Remarks4'] == True) & (
                       New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = '5_GSTIN_Only_Tax_Matched'

        New_10.loc[(New_10['Final_Remarks'].isnull()) & (New_10['ConcatColumn1_y'] != 0) & (
                    New_10['Diff1'] > 0), 'Final_Remarks'] = 'Excess_Tax_in_Portal'
        New_10.loc[(New_10['Final_Remarks'].isnull()) & (New_10['ConcatColumn1_y'] != 0) & (
                    New_10['Diff1'] < 0), 'Final_Remarks'] = 'Excess_Tax_in_Invoice'

        New_10.loc[(New_10['Final_Remarks'].isnull()) & (New_10['ConcatColumn2a_y'] != 0) & (
                    New_10['Diff2'] > 0), 'Final_Remarks'] = 'Excess_Tax_in_Portal'
        New_10.loc[(New_10['Final_Remarks'].isnull()) & (New_10['ConcatColumn2a_y'] != 0) & (
                    New_10['Diff2'] < 0), 'Final_Remarks'] = 'Excess_Tax_in_Invoice'

        New_10.loc[(New_10['Final_Remarks'].isnull()), 'Final_Remarks'] = 'Available_in_Portal_Not_In_Purchse_register'

        invoice_output = New_9[
            ["ctinno", "FY", "gstin", "invoice_date", "invoiceno", "invoiceno_New1", "taxablevalue", "totaltax",
             "Datasource", "Final_Remarks", "cgst", "sgst", "igst", ]]
        portal_output = New_10[
            ["ctinno", "FY", "gstin", "invoice_date", "invoiceno", "invoiceno_New1", "taxablevalue", "totaltax",
             "Datasource", "Final_Remarks", "cgst", "sgst", "igst"]]
        consol_output = portal_output.append(invoice_output)


        df11 = pd.pivot_table(consol_output, index=['Final_Remarks', 'ctinno', 'invoiceno'], columns=['Datasource'],
                              values=['totaltax'],
                              aggfunc='sum', fill_value=0, margins=True, margins_name='GrandTotal')
        df11.drop(columns='GrandTotal', axis=1, level=1, inplace=True)

        df12 = pd.pivot_table(consol_output, index=['Final_Remarks', 'FY', ], columns=['Datasource'],
                              values=['totaltax'],
                              aggfunc='sum', fill_value=0, margins=True, margins_name='GrandTotal')
        df12.drop(columns='GrandTotal', axis=1, level=1, inplace=True)

        #df12.plot.bar(rot=0, subplots=True)





        with tempfile.TemporaryDirectory() as tmpdirname:
            path = os.path.join(tmpdirname, 'sample.xlsx')
            print('created temporary directory', tmpdirname)
            with pd.ExcelWriter(path) as writer:
                consol_output.to_excel(writer, sheet_name='Main_Output')
                df11.to_excel(writer, sheet_name='Aggregation')
                df12.to_excel(writer, sheet_name='Summary')

                


            fromaddr = "*****@*****.**"
            toaddr = "*****@*****.**"

            # instance of MIMEMultipart
            msg = MIMEMultipart()

            # storing the senders email address
            msg['From'] = fromaddr

            # storing the receivers email address
            msg['To'] = toaddr

            # storing the subject
            msg['Subject'] = "Hello XYZ"

            # string to store the body of the mail
            body = "Reconciliation Report"

            # attach the body with the msg instance
            msg.attach(MIMEText(body, 'plain'))

            # open the file to be sent
            filename = "sample.xlsx"
            attachment = open(path, "rb")


            # instance of MIMEBase and named as p
            p = MIMEBase('application', 'octet-stream')

            # To change the payload into encoded form
            p.set_payload((attachment).read())

            # encode into base64
            encoders.encode_base64(p)

            p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

            # attach the instance 'p' to instance 'msg'
            msg.attach(p)
            attachment.close()

            # creates SMTP session
            s = smtplib.SMTP('smtp.gmail.com', 587)

            # start TLS for security
            s.starttls()

            # Authentication
            s.login(fromaddr, "abc@123")

            # Converts the Multipart msg into a string
            text = msg.as_string()

            # sending the mail
            s.sendmail(fromaddr, toaddr, text)

            s.quit()
            msg1="Mail Sent Successfully"




    return render(request, 'excel_reader/home.html', {'Message':msg1})
            # storing the senders email address
            msg['From'] = fromaddr

            # storing the receivers email address
            msg['To'] = email

            # storing the subject
            msg['Subject'] = "Subject of the Mail"

            # string to store the body of the mail
            body = "Body_of_the_mail"

            # attach the body with the msg instance
            msg.attach(MIMEText(body, 'plain'))

            # open the file to be sent
            attachment = image1

            # instance of MIMEBase and named as p
            p = MIMEBase('application', 'octet-stream')

            # attach the instance 'p' to instance 'msg'
            msg.attach(p)

            # Converts the Multipart msg into a string
            text = msg.as_string()

            # sending the mail
            server.sendmail(fromaddr, toaddr, text)

Example #45
0
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=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.
    """
    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, "plain")
    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())
        fp.close()

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

    return {
        "raw": base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")
    }
Example #46
0
def  byyyy(ordered_items,hhh,user_name):
  user_id=user_name
  final_amount=hhh
  s=ordered_items
  s=s.split(',')
  length = len(s)
  i=0
  list1=[];
  while(i<length):
    list1.append([s[i],s[i+1],s[i+2]])
    i=i+3
  con=sql.connect("test.db")
  cur=con.cursor()
  cur.execute('SELECT mobileno FROM users WHERE rollno = ?',(user_id,))
  mobile_number=cur.fetchone()[0]
  cur.execute('SELECT email FROM users WHERE rollno = ?',(user_id,))
  email_id=cur.fetchone()[0]
  con.close()
  con1=sql.connect("test.db")
  cur1=con1.cursor()
  cur1.execute("INSERT INTO payment_history (order_no,User,payment,mobileno,emailid) VALUES (?,?,?,?,?)",(order_no,user_id,final_amount,mobile_number,email_id) )
  con1.commit()          
  con1.close()
  file_name=str(order_no)
  file_name=file_name+".txt"
  f=open(file_name,"w")
  t=PrettyTable(['S.NO','ITEM NAME','QUANTITY'])
  len1=len(list1)
  j=1
  i=0
  while(i<len1):
    t.add_row([list1[i][0],list1[i][1],list1[i][2]])
    i=i+1
  r=str(t)
  f.write("\nCU-PAL\n\n")
  f.write("User Name %s"%user_id)
  f.write("\nEmail-id %s"%email_id)
  f.write("\n Your Order has been placed and your order number is %s\n"%order_no)
  f.write(r)
  f.write("\nTOTAL AMOUNT PAYED %s" % final_amount)
  f.write("\n Please go to the counter and collect you order\nTHANK YOU!!")
  f.close()
  fromaddr = "*****@*****.**"
  toaddr = email_id
  msg = MIMEMultipart()
  msg['From'] = fromaddr
  msg['To'] = toaddr
  msg['Subject'] = "CU-PAL(YOUR ORDER HAS BEEN PLACED)"
  body = "\nThank You for using our application\nYour Order Number is %s \nRegards\nCU-PAL"%order_no
  msg.attach(MIMEText(body, 'plain'))
  filename = file_name
  path="/home/sushant/Desktop/flask_test/"+file_name
  attachment = open(path, "rb")
  p = MIMEBase('application', 'octet-stream')
  p.set_payload((attachment).read())
  encoders.encode_base64(p)
  p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
  msg.attach(p)
  s = smtplib.SMTP('smtp.gmail.com', 587)
  s.starttls()
  s.login(fromaddr, "sushant123")
  text = msg.as_string()
  s.sendmail(fromaddr, toaddr, text)
  s.quit()
  return render_template('bye.html')
Example #47
0
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromadd = 'sender_email'
toadd = 'reciever_emailaddress'

msg = MIMEMultipart()
msg['FROM'] = fromadd
msg['TO'] = toadd
msg['SUBJECT'] = 'TEST SUBJECT'
body = 'TEST Body'
msg.attach(MIMEText(body, 'plain'))
filename = 'your file name with extension'
attachment = open(r'fiull file_path', 'rb')
p = MIMEBase('application', "pdf", Name=filename)
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
msg.attach(p)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.login(fromadd, 'your password')
text = msg.as_string()
s.sendmail(fromadd, toadd, text)
s.quit()
print("Email sent!")
def send_email():
    try:
        email = ' '  #write your email
        send_to_email = ' '  #write senders email
        subject = 'Report Summary'
        message = 'Details about untagged EC2 instances and untagged EBS volumes'
        file_location1 = '/home/shashanksrivastava/Downloads/reports/untagged_instances.csv'
        file_location1 = '/home/shashanksrivastava/Downloads/reports/untagged_volumes.csv'
        message_html = """
		<html>
			<body>
				<h1 style="color:rgb(51,51,51);font-weight:300;margin-top:20px;margin-bottom:10px">Digital AWS Accounts</h1>
				<hr style="border-style:solid none none;border-top-width:1px;border-top-color:rgb(221,221,221);margin-top:20px;					margin-bottom:20px;color:#5191d1;border:1px solid #5191d1;margin:0px 0px 20px 0px">
				<table style="font-family:&quot;Lucida Grande&quot;,Arial;font-size:18px;width:100%;border-spacing:0px">
		  			<tbody>
		  				<tr>
		      				<td><b>Account Name<b></td>
		      				<td style="text-align:left">
        		  				<b>Account Owner</b>
		      				</td>

 		     				<td style="text-align:left"><b>Cost($)</b></td>
   						</tr>
		    			<tr>
		      				<td>Oauth-AWS</td>
		      				<td style="text-align:left">
        		  				Shashank Srivastava
		      				</td>
 		     				<td style="text-align:left">{cost}</td>
   						</tr>
		        	</tbody>
	     		</table>
	     	</body>
	    </html>
		"""
        global untagged_ec2
        global untagged_ebs

        new_msg = message_html.format(cost=total_cost)
        msg = MIMEMultipart('alternative')
        msg['From'] = email
        msg['To'] = send_to_email
        msg['Subject'] = subject

        msg.attach(MIMEText(message, 'plain'))
        msg.attach(MIMEText(new_msg, 'html'))

        filename1 = os.path.basename(file_location1)
        filename2 = os.path.basename(file_location2)
        filename3 = os.path.basename(file_location3)
        filename4 = os.path.basename(file_location4)
        file_list = [filename1, filename2, filename3, filename4]
        for f in file_list:
            attachment = open(f, "rb")
            part = MIMEBase('application', 'octet-stream')
            part.set_payload((attachment).read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            "attachment; filename= %s" % f)
            msg.attach(part)

        smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(email, app_password)
        text = msg.as_string()
        smtpObj.sendmail(email, send_to_email, text)
        smtpObj.quit()
    except:
        print 'Something went wrong...'
def send_email():

    #clear the text output
    for i in range(5):
        print "\n."

    testMode = settings.testMode
    filename = settings.login['xls_file']
    gmail_password = settings.login['gmail_password']
    me = settings.login['gmail_username']
    you = settings.login['bandsintown_bulkupload_email']

    print "\n\n_________________________"
    print "_______BANDSINTOWN_______"
    print "_________________________\n"

    #email yourself in testmode rather than actually sending test gig xls to BandsInTown
    if testMode:
        print "TEST MODE: emailing from:{} to:{} instead of to:{}\n".format(
            me, me, you)
        you = me

    #CC the sender
    cc = me

    # instance of MIMEMultipart
    print 'Assembling the email for BandsInTown...'

    msg = MIMEMultipart()
    msg['Subject'] = ''
    msg['From'] = me
    msg['To'] = you
    msg['Cc'] = me
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # string to store the body of the mail
    body = "Upcoming Gigs"

    # attach the body with the msg instance
    msg.attach(MIMEText(body, 'plain'))

    print 'Loading the .XLS file...',
    # open the file to be sent
    attachment = open(filename, "rb")

    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'octet-stream')

    # To change the payload into encoded form
    p.set_payload((attachment).read())

    # encode into base64
    encoders.encode_base64(p)

    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    print 'Attaching...'
    # attach the instance 'p' to instance 'msg'
    msg.attach(p)

    print 'Contacting Gmail Server...',
    # creates SMTP session
    s = smtplib.SMTP('smtp.gmail.com', 587)

    print 'Securely...',
    # start TLS for security
    s.starttls()

    print 'Logging In...'
    # Authentication
    s.login(me, gmail_password)

    print 'Adding Attachment to Email Message...'
    # Converts the Multipart msg into a string
    text = msg.as_string()

    # sending the mail
    print 'Sending from {} to {}...'.format(me, you)
    s.sendmail(me, [you, cc], text)

    # terminating the session
    print 'Closing email...'
    s.quit()
    print "______________________"
    print "______________________"
    print "______________________"
    return
Example #50
-1
def sendEmail():
    #This sends an email containing any type of attachment
    emailfrom = "*****@*****.**"
    emailto = ["*****@*****.**"]
    fileToSend = "/home/pi/picurity-system/videos/SurveillanceFootage.h264"
    username = "******"
    password = "******"
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ", ".join(emailto)
    msg["Subject"] = "Motion Has Been Detected: View Attached Clip"
    msg.preamble = "Motion Has Been Detected: View Attached Clip"
    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"
    maintype, subtype = ctype.split("/", 1)
    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")
    server.starttls()
    server.login(username,password)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()
Example #51
-1
    def run(self):
        account = str(self.account)
        # Create the enclosing (outer) message
        outer = MIMEMultipart()
        outer['Subject'] = 'mask{0}mask_{1}'.format(self.index, str(self.filename))
        outer['To'] = account
        outer['From'] = account
        outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        fp = open(str(self.filename), 'rb')
        msg = MIMEBase(maintype, subtype)
        #msg.set_payload(encodebytes(fp.read()).decode())
        msg.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(msg)
    #    msg.add_header('Content-Transfer-Encoding', 'base64')
        msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(str(self.filename)))
        outer.attach(msg)
        # Send the message
        composed = outer.as_string()
        if DEBUG:
            fp = open("./output", 'w')
            fp.write(composed)
            fp.close()
        else:
            s = smtplib.SMTP()
            s.set_debuglevel(DEBUG)
            s.connect(self.smtp_server)
            s.login(account, self.password)
            s.sendmail(account, account, composed)
            s.quit()