Skip to content Skip to sidebar Skip to footer

Fail To Send Mail Using Javamail Api

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 te

Solution 1:

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.ThreadPolicypolicy=newStrictMode.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;

publicclassSenderextendsActivity {
    Button Send;
    TextView text;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_login);

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

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

        Send.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stubnewSendMail().execute();
            }
        });

    }

    privateclassSendMailextendsAsyncTask<String, Void, Integer> 
    { 
        ProgressDialogpd=null;
        Stringerror=null;
        Integer result;

        @OverrideprotectedvoidonPreExecute() {
            // TODO Auto-generated method stubsuper.onPreExecute();
            pd = newProgressDialog(Sender.this);
            pd.setTitle("Sending Mail");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.show();
        }

        @Overrideprotected Integer doInBackground(String... params) { 
            // TODO Auto-generated method stub MailSendersender=newMailSender("yourmail@gmail.com", "yourpassword"); 

            sender.setTo(newString[]{"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");
                    return1;
                } else {
                    return2;
                }
            } catch (Exception e) {   
                error = e.getMessage();
                Log.e("SendMail", e.getMessage(), e);    
            }

            return3; 
        } 

        protectedvoidonPostExecute(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();
            } elseif(result==2) {
                Toast.makeText(Sender.this,
                        "Email was not sent.", Toast.LENGTH_LONG).show();
            } elseif(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;

publicclassMailSenderextendsAuthenticator {
    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;

    privateboolean auth;
    privateboolean debuggable;

    private Multipart multi;

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

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

        debuggable = false;
        auth = true;

        multi = newMimeMultipart();

        // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.MailcapCommandMapmc= (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); 
    }

    publicMailSender(String user, String password){
        this();      
        this.user = user;
        this.password = password;   
    }

    publicbooleansend()throws Exception {
        Propertiesprops= setProperties();

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

            MimeMessagemsg=newMimeMessage(session);

            msg.setFrom(newInternetAddress(from));

            InternetAddress[] addressTo = newInternetAddress[to.length];
            for(int i=0; i<to.length; i++){
                addressTo[i] = newInternetAddress(to[i]);
            }

            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
            msg.setSubject(subject);
            msg.setSentDate(newDate());

            BodyPartmessageBodyPart=newMimeBodyPart();
            messageBodyPart.setText(body);
            multi.addBodyPart(messageBodyPart);

            msg.setContent(multi);

            Transporttransport= session.getTransport("smtps");
            transport.connect(host, 465, user, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            returntrue;
        } catch (Exception e) {
            e.printStackTrace();
            returnfalse;
        }
    }

    publicvoidaddAttachment(String filename)throws Exception {
        BodyPartmessageBodyPart=newMimeBodyPart();
        DataSourcesource=newFileDataSource(filename);
        messageBodyPart.setDataHandler(newDataHandler(source));
        messageBodyPart.setFileName(filename);

        multi.addBodyPart(messageBodyPart);
    }

    @Overridepublic PasswordAuthentication getPasswordAuthentication() { 
        returnnewPasswordAuthentication(user, password); 
      }

    private Properties setProperties() {
        Propertiesprops=newProperties();

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

    publicvoidsetTo(String[] toAddress) {
        this.to = toAddress;
    }

    publicvoidsetFrom(String fromAddress) {
        this.from = fromAddress;
    }

    publicvoidsetSubject(String subject) {
        this.subject = subject;
    }

    publicvoidsetBody(String body) { 
        this.body = body; 
    }
}

Solution 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..

Solution 3:

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.ThreadPolicypolicy=newStrictMode.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.

Solution 4:

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

Solution 5:

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:

privateclassSendMailextendsAsyncTask<String, Void, String>
{

    @OverrideprotectedStringdoInBackground(String... params) {
        // TODO Auto-generated method stubtry {    
            MailSender sender = newMailSender("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);    
        }

        returnnull;
    }

}

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

Post a Comment for "Fail To Send Mail Using Javamail Api"