Exemplo n.º 1
0
    def test_real_mail_aiosmtpd(self):
        """ Test sending messages with a real-world SMTPD server """
        if aiosmtpd is None:
            self.skipTest('aiosmtpd not available')

        # Start an smtp server
        mail_handler = StashingHandler()
        controller = Controller(mail_handler, loop=None,
                                hostname='localhost', port=self.smtpd_port)
        controller.start()

        # Give it time to settle
        sleep(0.5)

        # Initialize a Postman
        postman = Postman('*****@*****.**',
                          NoLoginSMTP('localhost', self.smtpd_port, None, None))

        # Send messages
        with postman.connect() as c:
            # Send plaintext message
            msg = Message(['*****@*****.**'], 'Subject', 'HTML message')
            c.sendmail(msg)

            # Send unicode message
            msg = Message(['*****@*****.**'], u'Håkon', u'Håkon')
            c.sendmail(msg)

        # Done
        controller.stop()

        # Test
        self.assertEqual(len(mail_handler.mail), 2)
Exemplo n.º 2
0
    def __init__(self, config, januapath):
        self.config = config
        self.postman = None
        self.januapath = januapath

        if self.config.enable:
            connection = ESMTPConnection(config.smtp_host,
                                         config.smtp_port,
                                         config.smtp_username,
                                         config.smtp_password,
                                         local_hostname=None,
                                         ssl=config.smtp_ssl,
                                         tls=config.smtp_tls,
                                         timeout=config.smtp_timeout)
            self.postman = Postman(config.mail_from, connection)
Exemplo n.º 3
0
    def test_smtp(self):
        # Fake
        msg = Message(['*****@*****.**'], 'Test')
        postman = Postman('*****@*****.**',
                          SMTPConnection(
                              'smtp.gmail.com', 587,
                              '*****@*****.**', 'wrong',
                              tls=True))

        # try to connect: an error should occur
        try:
            with postman.connect() as c:
                raise AssertionError('Exception not raised')
        except smtplib.SMTPAuthenticationError as e:
            self.assertEqual(e.smtp_code, 535)
            self.assertIn('Username and Password not accepted', e.smtp_error)
Exemplo n.º 4
0
    def test_real_mail_smtpd(self):
        """ Test sending messages with a real SMTPD server """
        # port+1 because python can't let it go.. :) hack?
        smtp_server = TestingSMTPServer(port=self.smtpd_port+1)
        smtp_server.start()
        sleep(0.5)

        # Initialize a Postman
        postman = Postman('*****@*****.**',
                          NoLoginSMTP('localhost', self.smtpd_port+1, None, None))

        # Send messages
        with postman.connect() as c:
            # Send unicode message
            c.sendmail(Message(['*****@*****.**'], u'Håkon', u'Håkon'))

        # Test
        self.assertIsNotNone(smtp_server.received_data)

        # Clean-up
        smtp_server.close()
        smtp_server.join()
Exemplo n.º 5
0
    def test_smtp(self):
        # Set socket timeout (because in some cases the test hangs for 120 seconds)
        socket.setdefaulttimeout(2.0)
        self.addCleanup(socket.setdefaulttimeout, None)

        # Fake
        msg = Message(['*****@*****.**'], 'Test')
        postman = Postman(
            '*****@*****.**',
            SMTPConnection('smtp.gmail.com',
                           587,
                           '*****@*****.**',
                           'wrong',
                           tls=True))

        # try to connect: an error should occur
        try:
            with postman.connect() as c:
                raise AssertionError('Exception not raised')
        except smtplib.SMTPAuthenticationError as e:
            self.assertEqual(e.smtp_code, 535)
            self.assertIn(b'Username and Password not accepted', e.smtp_error)
Exemplo n.º 6
0
    def test_real_mail_smtpd(self):
        """ Test sending messages with a real SMTPD server """
        # port+1 because python can't let it go.. :) hack?
        smtp_server = TestingSMTPServer(port=self.smtpd_port + 1)
        smtp_server.start()
        sleep(0.5)

        # Initialize a Postman
        postman = Postman(
            '*****@*****.**',
            NoLoginSMTP('localhost', self.smtpd_port + 1, None, None))

        # Send messages
        with postman.connect() as c:
            # Send unicode message
            c.sendmail(Message(['*****@*****.**'], u'Håkon', u'Håkon'))

        # Test
        self.assertIsNotNone(smtp_server.received_data)

        # Clean-up
        smtp_server.close()
        smtp_server.join()
Exemplo n.º 7
0
    def test_real_mail_aiosmtpd(self):
        """ Test sending messages with a real-world SMTPD server """
        if aiosmtpd is None:
            self.skipTest('aiosmtpd not available')

        # Start an smtp server
        mail_handler = StashingHandler()
        controller = Controller(mail_handler,
                                loop=None,
                                hostname='localhost',
                                port=self.smtpd_port)
        controller.start()

        # Give it time to settle
        sleep(0.5)

        # Initialize a Postman
        postman = Postman(
            '*****@*****.**',
            NoLoginSMTP('localhost', self.smtpd_port, None, None))

        # Send messages
        with postman.connect() as c:
            # Send plaintext message
            msg = Message(['*****@*****.**'], 'Subject', 'HTML message')
            c.sendmail(msg)

            # Send unicode message
            msg = Message(['*****@*****.**'], u'Håkon', u'Håkon')
            c.sendmail(msg)

        # Done
        controller.stop()

        # Test
        self.assertEqual(len(mail_handler.mail), 2)
Exemplo n.º 8
0
    def test_smtp(self):
        # Fake
        msg = Message(['*****@*****.**'], 'Test')
        postman = Postman('*****@*****.**', None)  # It's never used anyway

        # Cannot use `None` as Connection
        self.assertRaises(AttributeError, postman.connect().__enter__)

        # Mock and test
        with postman.loopback() as lo:
            # Send
            with postman.connect() as c:
                c.sendmail(msg)

            # Check
            self.assertEqual(len(lo), 1)

        self.assertEqual(len(lo), 1)  # Still usable

        # Now fails again
        self.assertRaises(AttributeError, postman.connect().__enter__)
Exemplo n.º 9
0
def main():
    cls ()
    datiserver, cartellelavoro = configurazionesmtp ()
    listamail= letturamaillist (cartellelavoro['mailist'])
    print "inserimento dati preparatori"
    t= int(raw_input ("inserisci l'intervallo dell'attesa tra l'invio di una mail e l'altra, in minuti(es. 3 o 4 o 5 minuti):" ))
    ora=0
    minuti=t* len (listamail)
    #calcolo tempo necessario per l'invio della mail.
    if (len(listamail)*t)>=60 :
        ora= int((len(listamail)*t)/60)
        minuti= len(listamail)*t%60
    print "tempo necessario per completare l'invio di ", len(listamail),"mail:" ,ora,"ora/e:",minuti," minuto/i circa."
    spegnimento_macchina=raw_input("vuoi che spegnere il pc finito l'invio?(S/N or s/n):")

   #caricamento dati gia' inseriti
    cls()
    print 'inserimento o caricamento dati messaggio'
    scelta_messaggio= raw_input ("ci sono dei dati gia' predisposti li vuoi caricare e usare quei dati? (S/N o s/n):")
    if scelta_messaggio == "s" or scelta_messaggio =="S":
        stream =open ('c:\\newsletter\\messaggio_html\\datimessaggio.yaml','r')
        descrizione_foto= yaml.load (stream)
        stream.close()
    elif scelta_messaggio == "n" or scelta_messaggio== "N" :
#caricamentopaginahtml da inviare nel messaggio di posta.
        messaggiohtml= caricamentopagina (cartellelavoro['messaggio'])
        descrizione_foto= dict ()
        #inserimento oggetto messaggio
#scelta foto
        foto= elencofile (cartellelavoro['messaggio'])
        solo_foto= [n for n in foto if string.find(n,'jpg')!=-1 ]
        descrizione_foto['oggetto']= raw_input ("inserisci l'oggetto della email/newsletter:")
        for i, listafoto in enumerate (solo_foto,start=1):
            print i, listafoto, '\n'
        descrizione_foto['foto']= solo_foto[int(raw_input ("inserisci il numero della foto corrispondente:"))-1]
        descrizione_foto['titolo']= raw_input ("inserisci il titolo della descrizione dell'immobile (es.:'singola, appartamento, villetta ecc.): ")
        descrizione_foto['zona'] = raw_input ("inserisci dove si trova l'immobile (es. lido Nazioni, Lido Pomposa, Comacchio ecc.):")
        descrizione_foto['descrizione_breve'] = raw_input("inserisci una descrizione breve dell'immobile:")
        descrizione_foto['descrizione']= raw_input ("inserisci una descrizione piu' completa dell'immobile:")
        descrizione_foto['link']= raw_input ('inserisci il link per il bottone dettaglio:')
        descrizione_foto['paginahtml'] = messaggiohtml
        descrizione_foto['percentuale']= '%'
        dati_messaggio= open (cartellelavoro['messaggio']+'\\'+'datimessaggio.yaml','w')
        yaml.dump (descrizione_foto,dati_messaggio)
        dati_messaggio.close()
    messaggiodefinitivo = descrizione_foto ['paginahtml'] % descrizione_foto
    cls()
    #['foto'], descrizione_foto['titolo'],descrizione_foto['zona'],descrizione_foto['descrizione_breve'],descrizione_foto['descrizione']
#preparazionesmtp server
    smtp_host=datiserver['nomeserver']
    smtp_port=datiserver['porta']
    smtp_mode=datiserver['metodosicurezza']
    smtp_login=datiserver['login']
    smtp_password=datiserver ['password']
    mittente = datiserver ['mailaddress']
#caricamento elenco dei nomi dei file immagini per la pagina html.
    foto= elencofile (cartellelavoro['messaggio'])
    solo_foto= [n for n in foto if string.find(n,'gif')!=-1 ]
    solo_foto.extend ([n for n in foto if string.find(n,'jpg')!=-1])
    solo_foto.extend([n for n in foto if string.find(n,'png')!=-1])
    integrazione=[]

    for nomefile in solo_foto:
        #ImageAttachment(nomefile, open(cartellelavoro['messaggio']+'\\'+nomefile,'rb').read(), 'inline')
        integrazione.append(ImageAttachment(nomefile, open(cartellelavoro['messaggio']+'\\'+nomefile,'rb').read(), 'inline'))
    # Initialize a postman with SMTP connection to GMail
    postman = Postman(mittente,
                SMTPConnection(smtp_host, smtp_port,smtp_login,smtp_password,tls=True))
    cls()
    print 'invio mail alla mail list.'
    print "tempo necessario per completare l'invio di ", len(listamail),"mail:" ,ora,"ora/e:",minuti," minuto/i circa escluso il tempo per l'invio di ogni singola e-mail."
    if spegnimento_macchina == "S" or spegnimento_macchina == "s":
        print "la Macchina verra' spenta a fine lavoro"
    for destinatari in listamail:
        destinatario = destinatari [1]
#Composizione messaggio
        print "invio a:", destinatario
        messaggio = Message([destinatario],descrizione_foto['oggetto'],
          messaggiodefinitivo,attachments = integrazione)
# Send everything we have
        with postman.connect() as c:
            c.sendmail(messaggio)
            print "inviato con Successo"
        tempoattesa(t)

    #preparazione mail messaggio e scelta delle immagini.
    if spegnimento_macchina == "S" or spegnimento_macchina == "s":
        os.system ("c:\\windows\\system32\\shutdown.exe /s")
    exit
Exemplo n.º 10
0
class JanuaMailer():
    def __init__(self, config, januapath):
        self.config = config
        self.postman = None
        self.januapath = januapath

        if self.config.enable:
            connection = ESMTPConnection(config.smtp_host,
                                         config.smtp_port,
                                         config.smtp_username,
                                         config.smtp_password,
                                         local_hostname=None,
                                         ssl=config.smtp_ssl,
                                         tls=config.smtp_tls,
                                         timeout=config.smtp_timeout)
            self.postman = Postman(config.mail_from, connection)

    def get_template(self, name):
        path = os.path.join(self.januapath, 'mail_template',
                            self.config.mail_language.upper(), name)
        if not os.path.exists(path):
            raise MailError('Template %s not found' % name)

        template = Template.from_directory(path,
                                           subject_name='subject.txt',
                                           text_name='body.txt',
                                           html_name='body.html')
        template.set_renderer(UnicodePythonTemplateRenderer)
        return template

    def sendmail(self, mailobj):
        if not isinstance(mailobj, MailObj):
            raise MailError('argument must be MailObj')

        if not self.config.enable:
            raise MailError('Mail option has been disabled, dropping mail ...')

        subject = mailobj.subject
        message = mailobj.message
        if isinstance(mailobj.to, list):
            to = mailobj.to
        else:
            to = [mailobj.to]
        template = mailobj.template
        template_args = mailobj.template_args
        reply_to = mailobj.reply_to
        bcc = mailobj.bcc

        if self.postman:
            if template:
                tmpl = self.get_template(template)
                msg = tmpl(to, template_args, reply_to=reply_to, bcc=bcc)
            else:
                msg = Message(to,
                              subject,
                              text=message,
                              reply_to=reply_to,
                              bcc=bcc)
            if msg:
                try:
                    with self.postman.connect() as c:
                        c.sendmail(msg)
                except Exception, err:
                    raise MailError(err)
                return True
        return False