4

I have the following code which is attempting to send an email in background. I have made use of a textview to see the exception. However, although nothing is being shown in the textview, I also cannot receive the mail. So I am not sure whether the mail has been delivered successfully or not. Can anyone give help to me?

Based on the suggestions, I have modified my program as following:

new Sender.java

public class Sender extends Activity {
    Button Send;
    TextView text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sender);

        Send = (Button) findViewById(R.id.mail);
        text = (TextView) findViewById(R.id.textView1);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        Send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new SendMail().execute();
            }
        });

    }

    private class SendMail extends AsyncTask<String, Void, String> 
    { 
        ProgressDialog pd = null;
        String error = null;
        Integer result;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(Sender.this);
            pd.setTitle("Uploading");
            pd.setMessage("Uploading logs. Please wait");
            pd.setCancelable(false);
            pd.show();
        }

        @Override 
        protected String doInBackground(String... params) { 
            // TODO Auto-generated method stub 

            MailSender sender = new MailSender("me@gmail.com", "password"); 

            String[] toAddress = {"me@gmail.com"};
            sender.setTo(toAddress);
            sender.setFrom("me@gmail.com");
            sender.setSubject("Test mail");
            sender.setBody("This is the mail body");
            try {
                if(sender.send()) {
                    System.out.println("Message sent");
                    result = 1;
                } else {
                    result = 2;
                }
            } catch (Exception e) {   
                error = e.getMessage();
                Log.e("SendMail", e.getMessage(), e);    
            }

            result = 3; 
            return null;
        } 

        protected void onPostExecute() {
            pd.dismiss();
            if(error!=null) {
                text.setText(error);
            }
            if(result==1) {
                Toast.makeText(Sender.this,
                    "Email was sent successfully.", Toast.LENGTH_LONG)
                    .show();
            } else if(result==2) {
                Toast.makeText(Sender.this,
                        "Email was not sent.", Toast.LENGTH_LONG).show();
            } else if(result==3) {
                Toast.makeText(Sender.this,
                        "There was a problem sending the email.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }   
}

new MailSender.java

public class MailSender extends Authenticator {
    private String user;
    private String password;

    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 multi;

    public MailSender(){
        host = "smtp.gmail.com";
        port = "465";
        sport = "465";

        user = "";
        password = "";
        from = "";
        subject = "";
        body = "";

        debuggable = false;
        auth = true;

        multi = 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/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 MailSender(String user, String password){
        this();      
        user = user;
        password = password;   
    }

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

        try{
            Session session = Session.getInstance(props, this);
            session.setDebug(true);

            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());

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multi.addBodyPart(messageBodyPart);

            msg.setContent(multi);

            Transport transport = session.getTransport("smtps");
            transport.connect(host, 465, user, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        } catch (Exception e) {
            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);

        multi.addBodyPart(messageBodyPart);
    }

    @Override 
      public PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(user, password); 
      }

    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;
    }

    public void setTo(String[] toAddress) {
        this.to = toAddress;
    }

    public void setFrom(String fromAddress) {
        this.from = fromAddress;
    }

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

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

After I changed the programm, when I click the button, it stops at pre-execution state, displaying "Uploading logs. Please wait". Mail cannot be sent out.

And in error log:

08-14 16:26:29.872: I/System.out(22439): DEBUG: setDebug: JavaMail version 1.4.1
08-14 16:26:29.888: I/System.out(22439): DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1]
08-14 16:26:29.896: I/System.out(22439): DEBUG SMTP: useEhlo true, useAuth false
08-14 16:26:29.896: I/System.out(22439): DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
08-14 16:26:30.568: I/System.out(22439): 220 mx.google.com ESMTP nq6sm593334pbc.56
08-14 16:26:30.568: I/System.out(22439): DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
08-14 16:26:30.568: I/System.out(22439): EHLO localhost
08-14 16:26:30.716: I/System.out(22439): 250-mx.google.com at your service, [202.155.209.250]
08-14 16:26:30.716: I/System.out(22439): 250-SIZE 35882577
08-14 16:26:30.716: I/System.out(22439): 250-8BITMIME
08-14 16:26:30.716: I/System.out(22439): 250-AUTH LOGIN PLAIN XOAUTH
08-14 16:26:30.716: I/System.out(22439): 250 ENHANCEDSTATUSCODES
08-14 16:26:30.716: I/System.out(22439): DEBUG SMTP: Found extension "SIZE", arg "35882577"
08-14 16:26:30.716: I/System.out(22439): DEBUG SMTP: Found extension "8BITMIME", arg ""
08-14 16:26:30.716: I/System.out(22439): DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
08-14 16:26:30.716: I/System.out(22439): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
08-14 16:26:30.716: I/System.out(22439): DEBUG SMTP: Attempt to authenticate
08-14 16:26:30.724: I/System.out(22439): AUTH LOGIN
08-14 16:26:30.872: I/System.out(22439): 334 VXNlcm5hbWU6
08-14 16:26:30.872: I/System.out(22439): 
08-14 16:26:31.021: I/System.out(22439): 334 UGFzc3dvcmQ6
08-14 16:26:31.021: I/System.out(22439): 
08-14 16:26:31.169: I/System.out(22439): 334 UGFzc3dvcmQ6
08-14 16:26:31.177: I/System.out(22439): DEBUG SMTP: useEhlo true, useAuth false
08-14 16:26:31.177: I/System.out(22439): DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
08-14 16:26:31.552: D/dalvikvm(22439): GC_CONCURRENT freed 341K, 4% free 11097K/11527K, paused 13ms+3ms, total 37ms
08-14 16:26:31.794: I/System.out(22439): 220 mx.google.com ESMTP st6sm593199pbc.58
08-14 16:26:31.794: I/System.out(22439): DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
08-14 16:26:31.794: I/System.out(22439): EHLO localhost
08-14 16:26:31.943: I/System.out(22439): 250-mx.google.com at your service, [202.155.209.250]
08-14 16:26:31.943: I/System.out(22439): 250-SIZE 35882577
08-14 16:26:31.943: I/System.out(22439): 250-8BITMIME
08-14 16:26:31.943: I/System.out(22439): 250-AUTH LOGIN PLAIN XOAUTH
08-14 16:26:31.943: I/System.out(22439): 250 ENHANCEDSTATUSCODES
08-14 16:26:31.950: I/System.out(22439): DEBUG SMTP: Found extension "SIZE", arg "35882577"
08-14 16:26:31.950: I/System.out(22439): DEBUG SMTP: Found extension "8BITMIME", arg ""
08-14 16:26:31.950: I/System.out(22439): DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
08-14 16:26:31.950: I/System.out(22439): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
08-14 16:26:31.950: I/System.out(22439): DEBUG SMTP: Attempt to authenticate
08-14 16:26:31.950: I/System.out(22439): AUTH LOGIN
08-14 16:26:32.099: I/System.out(22439): 334 VXNlcm5hbWU6
08-14 16:26:32.099: I/System.out(22439): 
08-14 16:26:32.247: I/System.out(22439): 334 UGFzc3dvcmQ6
08-14 16:26:32.247: I/System.out(22439): 
08-14 16:26:32.403: I/System.out(22439): 334 UGFzc3dvcmQ6
08-14 16:27:00.200: I/Choreographer(22439): Skipped 35 frames!  The application may be doing too much work on its main thread.

As it does not work, so I try to hide the function onpreexecute, but nothing changes, mail cannot be sent, here are the messages in error log:

08-14 16:31:18.958: I/System.out(22759): DEBUG: setDebug: JavaMail version 1.4.1
08-14 16:31:18.974: I/System.out(22759): DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1]
08-14 16:31:18.974: I/System.out(22759): DEBUG SMTP: useEhlo true, useAuth false
08-14 16:31:18.974: I/System.out(22759): DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
08-14 16:31:19.739: I/System.out(22759): 220 mx.google.com ESMTP og7sm597805pbb.62
08-14 16:31:19.739: I/System.out(22759): DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
08-14 16:31:19.739: I/System.out(22759): EHLO localhost
08-14 16:31:19.888: I/System.out(22759): 250-mx.google.com at your service, [202.155.209.250]
08-14 16:31:19.888: I/System.out(22759): 250-SIZE 35882577
08-14 16:31:19.888: I/System.out(22759): 250-8BITMIME
08-14 16:31:19.888: I/System.out(22759): 250-AUTH LOGIN PLAIN XOAUTH
08-14 16:31:19.888: I/System.out(22759): 250 ENHANCEDSTATUSCODES
08-14 16:31:19.888: I/System.out(22759): DEBUG SMTP: Found extension "SIZE", arg "35882577"
08-14 16:31:19.888: I/System.out(22759): DEBUG SMTP: Found extension "8BITMIME", arg ""
08-14 16:31:19.888: I/System.out(22759): DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
08-14 16:31:19.888: I/System.out(22759): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
08-14 16:31:19.888: I/System.out(22759): DEBUG SMTP: Attempt to authenticate
08-14 16:31:19.896: I/System.out(22759): AUTH LOGIN
08-14 16:31:20.044: I/System.out(22759): 334 VXNlcm5hbWU6
08-14 16:31:20.044: I/System.out(22759): 
08-14 16:31:20.185: I/System.out(22759): 334 UGFzc3dvcmQ6
08-14 16:31:20.185: I/System.out(22759): 
08-14 16:31:20.341: I/System.out(22759): 334 UGFzc3dvcmQ6
08-14 16:31:20.341: I/System.out(22759): DEBUG SMTP: useEhlo true, useAuth false
08-14 16:31:20.341: I/System.out(22759): DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
08-14 16:31:20.786: I/System.out(22759): 220 mx.google.com ESMTP og7sm597845pbb.62
08-14 16:31:20.786: I/System.out(22759): DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
08-14 16:31:20.786: I/System.out(22759): EHLO localhost
08-14 16:31:20.935: I/System.out(22759): 250-mx.google.com at your service, [202.155.209.250]
08-14 16:31:20.935: I/System.out(22759): 250-SIZE 35882577
08-14 16:31:20.935: I/System.out(22759): 250-8BITMIME
08-14 16:31:20.935: I/System.out(22759): 250-AUTH LOGIN PLAIN XOAUTH
08-14 16:31:20.935: I/System.out(22759): 250 ENHANCEDSTATUSCODES
08-14 16:31:20.943: I/System.out(22759): DEBUG SMTP: Found extension "SIZE", arg "35882577"
08-14 16:31:20.943: I/System.out(22759): DEBUG SMTP: Found extension "8BITMIME", arg ""
08-14 16:31:20.943: I/System.out(22759): DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
08-14 16:31:20.943: I/System.out(22759): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
08-14 16:31:20.943: I/System.out(22759): DEBUG SMTP: Attempt to authenticate
08-14 16:31:20.943: I/System.out(22759): AUTH LOGIN
08-14 16:31:21.091: I/System.out(22759): 334 VXNlcm5hbWU6
08-14 16:31:21.091: I/System.out(22759): 
08-14 16:31:21.239: I/System.out(22759): 334 UGFzc3dvcmQ6
08-14 16:31:21.239: I/System.out(22759): 
08-14 16:31:21.380: I/System.out(22759): 334 UGFzc3dvcmQ6
08-14 16:31:49.357: W/IInputConnectionWrapper(22759): clearMetaKeyStates on inactive InputConnection

I have already carry out the send operation in AsyncTask, may I ask why it still does not work?

Conrad
  • 933
  • 4
  • 19
  • 34

6 Answers6

6

as the log shows, you are calling network related tasks from main UI thread. You have to use AsyncTask for these communications. and remove the StrictMode by doing

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

StrictMode.setThreadPolicy(policy);

Also see my answer in this post regarding the usage of JavaMail API.

EDIT: Added the code inline here package com.max.mactest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Sender extends Activity {
    Button Send;
    TextView text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_login);

        Send = (Button) findViewById(R.id.cmdDoLogin);
        text = (TextView) findViewById(R.id.textView2);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        Send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new SendMail().execute();
            }
        });

    }

    private class SendMail extends AsyncTask<String, Void, Integer> 
    { 
        ProgressDialog pd = null;
        String error = null;
        Integer result;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(Sender.this);
            pd.setTitle("Sending Mail");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.show();
        }

        @Override 
        protected Integer doInBackground(String... params) { 
            // TODO Auto-generated method stub 

            MailSender sender = new MailSender("yourmail@gmail.com", "yourpassword"); 

            sender.setTo(new String[]{"tomail@gmail.com"});
            sender.setFrom("yourmail@gmail.com");
            sender.setSubject("Test mail");
            sender.setBody("This is the mail body");
            try {
                if(sender.send()) {
                    System.out.println("Message sent");
                    return 1;
                } else {
                    return 2;
                }
            } catch (Exception e) {   
                error = e.getMessage();
                Log.e("SendMail", e.getMessage(), e);    
            }

            return 3; 
        } 

        protected void onPostExecute(Integer result) {
            pd.dismiss();
            if(error!=null) {
                text.setText(error);
            }
            if(result==1) {
                Toast.makeText(Sender.this,
                    "Email was sent successfully.", Toast.LENGTH_LONG)
                    .show();
            } else if(result==2) {
                Toast.makeText(Sender.this,
                        "Email was not sent.", Toast.LENGTH_LONG).show();
            } else if(result==3) {
                Toast.makeText(Sender.this,
                        "There was a problem sending the email.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }   
}

updated MailSender

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.Authenticator;
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 MailSender extends Authenticator {
    private String user;
    private String password;

    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 multi;

    public MailSender(){
        host = "smtp.gmail.com";
        port = "465";
        sport = "465";

        user = "";
        password = "";
        from = "";
        subject = "";
        body = "";

        debuggable = false;
        auth = true;

        multi = 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/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 MailSender(String user, String password){
        this();      
        this.user = user;
        this.password = password;   
    }

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

        try{
            Session session = Session.getInstance(props, this);
            session.setDebug(true);

            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());

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multi.addBodyPart(messageBodyPart);

            msg.setContent(multi);

            Transport transport = session.getTransport("smtps");
            transport.connect(host, 465, user, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            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);

        multi.addBodyPart(messageBodyPart);
    }

    @Override 
      public PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(user, password); 
      }

    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;
    }

    public void setTo(String[] toAddress) {
        this.to = toAddress;
    }

    public void setFrom(String fromAddress) {
        this.from = fromAddress;
    }

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

    public void setBody(String body) { 
        this.body = body; 
    }
}
Community
  • 1
  • 1
sunil
  • 6,444
  • 1
  • 32
  • 44
  • So if I want to send email without using the existing email app in my device, I must use AsyncTask? Because I only follow the answer here:http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a ,you mean the example provided in this link will not work? – Conrad Aug 14 '12 at 06:09
  • if you are working with devices/emulators with API level greater than 9, then you cannot use Network related tasks (not only email app) in UI thread. Try my working sample – sunil Aug 14 '12 at 06:12
  • I see, okay, I will have a try first, see if I have any more problems. – Conrad Aug 14 '12 at 06:30
  • I have followed your code to rewrite the program, however, it stops at pre-execution state, displaying "Uploading logs. Please wait" I will update my program above, can you please help me to recognize where is the problem. – Conrad Aug 14 '12 at 08:17
  • I have copied your code to create a new project, if I use exactly your code, it works, but I have no idea where is the difference between mine and yours. – Conrad Aug 14 '12 at 09:31
  • 1
    @user1502740 i just updated your code and added in my answer itself. You made mistakes in `Asynctask` itself. You changed the return type as string but not updated the `onPostExecute` method accordingly. Notice the warnings in eclipse. Also with MailSender constructor, the assignment done as local, not to instance variables. Test the updated code – sunil Aug 14 '12 at 09:40
  • Thank you, it works now, after working on it for whole day, it finally sends the mail successfully, then I can try to send with attachment tomorrow. Thank you. At last may I ask one more question, if I want to send the mail from another mail hosting server, for example, yahoo, is it okay to do so by just changing host, port, my email and password? I mean, the structure of program does not need to change, right? – Conrad Aug 14 '12 at 10:08
  • @BhadreshDevani Nice to hear that it helped you. You can upvote this post if it seems helpful to you – sunil Aug 04 '14 at 14:25
2

ADD 3 jars found in the following link to your Android Project (Right Click Project- add External Jars)

Click Here - How to add External JARs

Run the project and check your recipient mail account for the mail. Cheers!!

Hope this helps..

Community
  • 1
  • 1
Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
  • I have already added them, as if wothout them, the eclipse will display error, I will not able to run my program. And I have also given permission to my program by add this to Manifest. So I dont know where is the error, and I cannot see any error in error log too. – Conrad Aug 14 '12 at 04:21
  • 1
    Try and change the id of Button in your layout and then try it out... Just a random thought that occurred... Might be there is an id conflict.. – Shekhar Chikara Aug 14 '12 at 04:26
  • I have changed it to mail, but still no mail can be received – Conrad Aug 14 '12 at 04:31
  • Are you using the same account by which you have created a Google account on your device?? – Shekhar Chikara Aug 14 '12 at 04:48
  • em...no, I borrow the device. This causes the app cannot run? – Conrad Aug 14 '12 at 04:57
  • 2
    Ok. Try this. I think you have a problem in MailSender.sendMail(). The problem is that no errors go outside of sendMail because you have try..catch inside it surrounding all the code. You should remove try..catch from sendMail. Otherwise it's impossible to detect errors. – Shekhar Chikara Aug 14 '12 at 05:03
  • So because I have try catch inside MailSender, therefore error cannot be seen in Sender class. Okay, let me remove it first – Conrad Aug 14 '12 at 05:09
  • user1502740 Pleasure... Don't forget to vote up if you find the help you needed... – Shekhar Chikara Aug 14 '12 at 05:59
2

Once check my working Email Application. I placed it Here

Before this please confirm that you have add

<uses-permission android:name="android.permission.INTERNET"/> in manifest

Community
  • 1
  • 1
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
  • Since my app does not work, so I read another reference here:http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_%28no_Intents%29_in_Android , seems it is using the same method as yours. And this has included function for adding attachments, which can match with my development purpose. I will have a try first, thank you! – Conrad Aug 14 '12 at 05:06
  • I have followed your code, but when I try to send, the app display "Email was not sent", no error messages in error log, so what is the reason it cannot be sent? here is the message showing in the error log "08-14 15:06:01.083: W/IInputConnectionWrapper(18627): clearMetaKeyStates on inactive InputConnection" – Conrad Aug 14 '12 at 07:09
  • add the permission – Ram kiran Pachigolla Aug 14 '12 at 08:38
  • ya, I have added it before, and now use AsyncTask also, but it does not work. I have no idea where are the errors. – Conrad Aug 14 '12 at 08:41
  • it will not send mail if there any error in the flow of code. i too face the problem but succeeded – Ram kiran Pachigolla Aug 14 '12 at 08:43
  • Whenever I click the button, it will start the AsyncTask, so I cannot know the flow of the code, how can I debug my program then? – Conrad Aug 14 '12 at 08:45
2

I guess you are working with API level 9+

You need to read about the StrictMode.

In your case you are trying to block the Network API on main UI thread so that's why the error occurs.

As a solution you can do this in your onCreate()

if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

To Read : This Blog , API Guidelines ,

Also Read about AsyncTask and use it to perform the task you are doing on main thread.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • After I add the block of code you mentioned, no error messages anymore, but it displays that "The application is doing too much in its main thread" – Conrad Aug 14 '12 at 06:29
  • Yes because you are doing so.. you need to use `AsyncTask` for that. – MKJParekh Aug 14 '12 at 06:40
0

For the NetworkOnMainThreadException, you need to use AsyncTask to perform the network activity. For this you can try and check out the following code. I haven't checked it, maybe you need to you a few tweaks in the code.

First create a class for AsyncTask like:

private class SendMail extends AsyncTask<String, Void, String>
{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {    
            MailSender sender = new MailSender("me@gmail.com", "password"); 
            sender.sendMail("Testing",    
                    "This is a test mail",    
                    "me@gmail.com",    
                    "me@gmail.com");    
        } catch (Exception e) {    
            text.setText(e.getMessage());
            Log.e("SendMail", e.getMessage(), e);    
        }

        return null;
    }

}

Now you can simply do your network activity task by calling new SendMail().execute() from within your onCreate method.

Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
0

if you are using asynchronous task for sending email just follow this

private class DownloadImageTask extends AsyncTask<String, String, Void> {
    int flag=0;
    protected Void doInBackground(String... arg0) {
        try{
            m = new Mail(emailaddress, password);
            m.setFrom(emailaddress.trim());
            toArr =   email.split(",");
            for(int i=0;i<toArr.length;i++)
            {
                                    // checking all emails entered are correct or not
                if (toArr[i].trim().matches(EMAIL_PATTERN))
                {
                    emailflag = true;
                }
                else
                {
                    emailflag = false;
                    break;
                }
            }
            m.setTo(toArr);
            if(!Subject.equals(""))
            {
                m.setSubject(txtSubject.getText().toString());
            }
            else   
            {
                m.setSubject("No Subject");
            }
            if(!EmailBody.equals(""))
            {
                m.setBody(txtEmailBody.getText().toString());
            }
            else  
            {
                m.setBody("No Message");                    
            }
            if(!attachefile.equals(""))
            {
                String[] temp;
                temp = attachefile.split("\\*");
                if(temp.length>0)
                {
                    for(int i =0; i < temp.length ; i++)
                    {   
                        m.addAttachment(temp[i]);
                    }
                }
            }
            if(emailflag && m.send())
            {
                flag=1;
                Intent intent = new Intent(SendEmail.this,SendEmail.class);
                startActivity(intent);
            }
            else
            {
                flag = 0;
            }

        }catch(Exception e){

                e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void result) 
    {
        progressDialog.dismiss();
        if(flag==1)
        {
            Toast.makeText(SendEmail.this, "Sent Successfully", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(SendEmail.this, "Failed please give correct email address", Toast.LENGTH_SHORT).show();
        }
    }
}

This is the regex for email..

private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78