0

I want to send Email without Intent;

I have codes shown below: these codes does't work and makes force close!

my MainActvity is:

package com.sendEmail.app;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;

public class MainActivity extends ActionBarActivity {

    private YahooMailSender m;
    GMailSender sender;

    final String FOLDER_ADDRESS = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "myPicture.jpg";

    String userid = "myGmail@gmail.com";
    String password = "myGmailPassword";
    String from = "myGmail@gmail.com";
    String to = "myYahooMal@yahoo.com";
    String subject = "Subject!";
    String body = "This is Test Email Service!";

    Button Send;
    TextView text;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Send = (Button) findViewById(R.id.button);
        text = (TextView) findViewById(R.id.textView);

        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(MainActivity.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

            sender = new GMailSender(userid, password);

            sender.setTo(new String[]{to});
            sender.setFrom(from);
            sender.setSubject(subject);
            sender.setBody(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(MainActivity.this,
                        "Email was sent successfully.", Toast.LENGTH_LONG).show();
            } else if(result==2) {
                Toast.makeText(MainActivity.this,
                        "Email was not sent.", Toast.LENGTH_LONG).show();
            } else if(result==3) {
                Toast.makeText(MainActivity.this,
                        "There was a problem sending the email.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}

and my GMailSender is:

package com.sendEmail.app;

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.Message;
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;
import java.util.Date;
import java.util.Properties;

public class GMailSender extends javax.mail.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 GMailSender(){
        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 GMailSender(String user, String password){
        this();
        this.user = user;
        this.password = password;
        host = "smtp.gmail.com";
        port = "465";
        sport = "465";
    }

    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, Integer.parseInt(port), 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;
    }
}

I think these codes in "GMailSender" have problem:

messageBodyPart.setText(body);

and

transport.sendMessage(msg, msg.getAllRecipients());

because when I make these codes comment, app doesn't show force close.

Please help me...

behzad-s
  • 1
  • 1
  • 1
    I don't think I would like you to do that at client level. Instead focus on server level technology. If you don't own any api infra. there are many free services such as https://www.mailgun.com/ – codebased Sep 10 '15 at 11:24
  • "and makes force close" -- use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Sep 10 '15 at 11:30
  • yes, please show the crash log – Jiang YD Sep 10 '15 at 11:31

0 Answers0