Autore Topic: Invio automatico di una mail  (Letto 899 volte)

Offline Ivan86

  • Utente junior
  • **
  • Post: 139
  • Respect: +1
    • Mostra profilo
  • Dispositivo Android:
    Samsung Galaxy S II
  • Sistema operativo:
    Windows 7
Invio automatico di una mail
« il: 07 Aprile 2013, 18:22:52 CEST »
0
Ciao.

Ho seguito un tutorial per l'invio di una mail in automatico.
In pratica voglio che alla registrazione, venga inviata una mail di conferma.
Non riesco a inviare la mail e mi da errore o warning.
Ho importato le seguenti librerie:
mail.jar
activation.jar
additionnal.jar

Posto un po' di codice.
Codice (Java): [Seleziona]
   private class InviaEmailTask extends AsyncTask<Void,Void,Void>  {
        @Override
            protected Void doInBackground(Void... params) {

                        Mail m = new Mail("info@miodominio.it", "miaPsw");
                        String[] toArr          = {aaa@gmail.com};
                       
                        m.setTo(toArr);
                        m.setFrom("info@miodominio.it");
                        m.setSubject("iscrizione");
                        m.setBody("corpo email");
                 
                try {
                       m.send();
                       pd.dismiss();
                       Toast.makeText(IscrizioneActivity.this, "Iscrizione avvenuta con successo", Toast.LENGTH_SHORT).show();
                       finish();
               } catch (Exception e1) {
                      e1.printStackTrace();
        }
Questo il warning:
Codice: [Seleziona]
04-07 15:28:34.322: W/System.err(2094): javax.mail.MessagingException: Could not connect to SMTP host: smtp.miodominio.it, port: 25;
04-07 15:28:34.322: W/System.err(2094):   nested exception is:
04-07 15:28:34.332: W/System.err(2094):         java.net.ConnectException: failed to connect to smtp.miodominio.it/62.xxx.xxx.xxx (port 465): connect failed: ETIMEDOUT (Connection timed out)
04-07 15:28:34.342: W/System.err(2094):         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
04-07 15:28:34.342: W/System.err(2094):         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
04-07 15:28:34.353: W/System.err(2094):         at javax.mail.Service.connect(Service.java:310)
04-07 15:28:34.353: W/System.err(2094):         at javax.mail.Service.connect(Service.java:169)
04-07 15:28:34.353: W/System.err(2094):         at javax.mail.Service.connect(Service.java:118)
04-07 15:28:34.353: W/System.err(2094):         at javax.mail.Transport.send0(Transport.java:188)
04-07 15:28:34.353: W/System.err(2094):         at javax.mail.Transport.send(Transport.java:118)
04-07 15:28:34.362: W/System.err(2094):         at it.tools.Mail.send(Mail.java:106)
04-07 15:28:34.362: W/System.err(2094):         at it.tesi.IscrizioneActivity$InviaEmailTask.doInBackground(IscrizioneActivity.java:369)
04-07 15:28:34.362: W/System.err(2094):         at it.tesi.IscrizioneActivity$InviaEmailTask.doInBackground(IscrizioneActivity.java:1)
04-07 15:28:34.362: W/System.err(2094):         at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-07 15:28:34.384: W/System.err(2094):         at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-07 15:28:34.384: W/System.err(2094):         at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-07 15:28:34.393: W/System.err(2094):         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-07 15:28:34.402: W/System.err(2094):         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-07 15:28:34.402: W/System.err(2094):         at java.lang.Thread.run(Thread.java:856)
04-07 15:28:34.402: W/System.err(2094): Caused by: java.net.ConnectException: failed to connect to smtp.miodominio.it/62.xxx.xxx.xxx (port 465): connect failed: ETIMEDOUT (Connection timed out)
04-07 15:28:34.412: W/System.err(2094):         at libcore.io.IoBridge.connect(IoBridge.java:114)
04-07 15:28:34.412: W/System.err(2094):         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
04-07 15:28:34.422: W/System.err(2094):         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
04-07 15:28:34.422: W/System.err(2094):         at java.net.Socket.connect(Socket.java:842)
04-07 15:28:34.422: W/System.err(2094):         at java.net.Socket.connect(Socket.java:785)
04-07 15:28:34.422: W/System.err(2094):         at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
04-07 15:28:34.432: W/System.err(2094):         at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
04-07 15:28:34.432: W/System.err(2094):         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
04-07 15:28:34.432: W/System.err(2094):         ... 15 more
04-07 15:28:34.442: W/System.err(2094): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
04-07 15:28:34.472: W/System.err(2094):         at libcore.io.Posix.connect(Native Method)
04-07 15:28:34.472: W/System.err(2094):         at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
04-07 15:28:34.472: W/System.err(2094):         at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
04-07 15:28:34.482: W/System.err(2094):         at libcore.io.IoBridge.connect(IoBridge.java:112)
04-07 15:28:34.491: W/System.err(2094):         ... 22 more

se invece nella AsyncTask facessi cosi:
Codice (Java): [Seleziona]
                    try {
                        if(m.send()) {
                                Toast.makeText(IscrizioneActivity.this, "Iscrizione avvenuta con successo", Toast.LENGTH_SHORT).show();
                                finish();
                    } else {
                      Toast.makeText(IscrizioneActivity.this, "Email non inviata", Toast.LENGTH_LONG).show();
                    }
                  } catch(Exception e) {
                    Toast.makeText(IscrizioneActivity.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
                    Log.e("MailApp", "Could not send email", e);
                  }
mi da il seguente errore:
Codice: [Seleziona]
04-07 15:17:30.102: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
04-07 15:17:30.102: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.FutureTask.run(FutureTask.java:239)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.lang.Thread.run(Thread.java:856)
04-07 15:17:30.102: E/AndroidRuntime(1871): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.os.Handler.<init>(Handler.java:197)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.os.Handler.<init>(Handler.java:111)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.widget.Toast$TN.<init>(Toast.java:324)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.widget.Toast.<init>(Toast.java:91)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.widget.Toast.makeText(Toast.java:238)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at it.tesi.IscrizioneActivity$InviaEmailTask.doInBackground(IscrizioneActivity.java:394)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at it.tesi.IscrizioneActivity$InviaEmailTask.doInBackground(IscrizioneActivity.java:1)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-07 15:17:30.102: E/AndroidRuntime(1871):         at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-07 15:17:30.102: E/AndroidRuntime(1871):         ... 4 more


La classe Mail è questa:
Codice (Java): [Seleziona]
package it.tools;

import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {
        private String _user;
        private String _pass;

        private String[] _to;
        private String _from;

        private String _port;
        private String _sport;

        private String _host;

        private String _subject;
        private String _body;

        private boolean _auth;

        private boolean _debuggable;

        private Multipart _multipart;

        public Mail() {
                _host = "smtp.miodominio.it"; // default smtp server
                _port = "25"; // default smtp port
                _sport = "465"; // default socketfactory port

                _user = ""; // username
                _pass = ""; // password
                _from = ""; // email sent from
                _subject = ""; // email subject
                _body = ""; // email body

                _debuggable = false; // debug mode on or off - default off
                _auth = true; // smtp authentication - default on

                _multipart = new MimeMultipart();

                // There is something wrong with MailCap, javamail can not find a
                // handler for the multipart/mixed part, so this bit needs to be added.
                MailcapCommandMap mc = (MailcapCommandMap) CommandMap
                                .getDefaultCommandMap();
                mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
                mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
                mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
                CommandMap.setDefaultCommandMap(mc);
        }

        public Mail(String user, String pass) {
                this();

                _user = user;
                _pass = pass;
        }

        public boolean send() throws Exception {
                Properties props = _setProperties();

                if (!_user.equals("") && !_pass.equals("") && _to.length > 0
                                && !_from.equals("") && !_subject.equals("")
                                && !_body.equals("")) {
                        Session session = Session.getInstance(props, this);

                        MimeMessage msg = new MimeMessage(session);

                        msg.setFrom(new InternetAddress(_from));

                        InternetAddress[] addressTo = new InternetAddress[_to.length];
                        for (int i = 0; i < _to.length; i++) {
                                addressTo[i] = new InternetAddress(_to[i]);
                        }
                        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

                        msg.setSubject(_subject);
                        msg.setSentDate(new Date());

                        // setup message body
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setText(_body);
                        _multipart.addBodyPart(messageBodyPart);

                        // Put parts in message
                        msg.setContent(_multipart);

                        // send email
                        Transport.send(msg);

                        return true;
                } else {
                        return false;
                }
        }

        public void addAttachment(String filename) throws Exception {
                BodyPart messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filename);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(filename);

                _multipart.addBodyPart(messageBodyPart);
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(_user, _pass);
        }

        private Properties _setProperties() {
                Properties props = new Properties();

                props.put("mail.smtp.host", _host);

                if (_debuggable) {
                        props.put("mail.debug", "true");
                }

                if (_auth) {
                        props.put("mail.smtp.auth", "true");
                }

                props.put("mail.smtp.port", _port);
                props.put("mail.smtp.socketFactory.port", _sport);
                props.put("mail.smtp.socketFactory.class",
                                "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");

                return props;
        }

        // the getters and setters
        public String getBody() {
                return _body;
        }

        public void setBody(String _body) {
                this._body = _body;
        }

        public String[] getTo() {
                return _to;
        }

        public void setTo(String[] toArr) {
                this._to = toArr;
        }

        public String getFrom() {
                return _from;
        }

        public void setFrom(String string) {
                this._from = string;
        }

        public String getSubject() {
                return _subject;
        }

        public void setSubject(String string) {
                this._subject = string;
        }

}

help :(

Offline bradipao

  • Moderatore globale
  • Utente storico
  • *****
  • Post: 4043
  • keep it simple
  • Respect: +567
    • Github
    • Google+
    • bradipao
    • Mostra profilo
  • Dispositivo Android:
    Nexus 5
  • Play Store ID:
    Bradipao
  • Sistema operativo:
    W7
Re:Invio automatico di una mail
« Risposta #1 il: 08 Aprile 2013, 07:58:33 CEST »
0
C'è un errore di fondo che potrebbe causare tutti i problemi che rilevi: non puoi accedere alla user interface (qualunque cosa di visivo) direttamente dalla doInBackground, devi usare la funzione (fornita dagli asynctask) per aggiornare la UI, la publishprogress.
NON rispondo a domande nei messaggi privati
Bradipao @ Play Store

Offline Ivan86

  • Utente junior
  • **
  • Post: 139
  • Respect: +1
    • Mostra profilo
  • Dispositivo Android:
    Samsung Galaxy S II
  • Sistema operativo:
    Windows 7
Re:Invio automatico di una mail
« Risposta #2 il: 08 Aprile 2013, 16:10:49 CEST »
0
Ciao
perdonami, ma a cosa mi serve la publishProgress?
Per aggiornare il progressBar nella Activity?

Se intendi questo, ho provato a rimuovere tutti i progress bar, progress dialog e toast della activity, ma il primo problema di warning che ho postato si è ripresentato.

Offline Ivan86

  • Utente junior
  • **
  • Post: 139
  • Respect: +1
    • Mostra profilo
  • Dispositivo Android:
    Samsung Galaxy S II
  • Sistema operativo:
    Windows 7
Re:Invio automatico di una mail
« Risposta #3 il: 13 Aprile 2013, 20:40:51 CEST »
0
Stavo impazzendo.
Avendo un dominio aruba ho dovuto per forza usare smtps.aruba.it
invece mi ostinavo a usare smtp.aruba.it
Quindi il problema era nella connessione e non nel codice ;)

Porca paletta
« Ultima modifica: 14 Aprile 2013, 11:58:05 CEST da Ivan86 »