Sending Email in Android using JavaMail API without using the default built-in app

0 votes

I am trying to create a mail sending application in Android.

If I use:

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

This will launch the built-in Android application; I'm trying to send the mail on button click directly without using this application.

Dec 4, 2018 in Java by Sushmita
• 6,910 points
3,158 views

1 answer to this question.

0 votes

Send e-mail in Android using the JavaMail API using Gmail authentication.

Steps to create a sample Project:

MailSenderActivity.java:

public class MailSenderActivity extends Activity {

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

        final Button send = (Button) this.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                try {   
                    GMailSender sender = new GMailSender("username@gmail.com", "password");
                    sender.sendMail("This is Subject",   
                            "This is Body",   
                            "user@gmail.com",   
                            "user@yahoo.com");   
                } catch (Exception e) {   
                    Log.e("SendMail", e.getMessage(), e);   
                } 

            }
        });

    }
}

GMailSender.java:

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   

    static {   
        Security.addProvider(new com.provider.JSSEProvider());   
    }  

    public GMailSender(String user, String password) {   
        this.user = user;   
        this.password = password;   

        Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.port", "465");   
        
        props.put("mail.smtp.socketFactory.port", "465");   
        props.put("mail.smtp.socketFactory.class",   
                "javax.net.ssl.SSLSocketFactory");   
        props.put("mail.smtp.socketFactory.fallback", "false");   
        props.setProperty("mail.smtp.quitwait", "false");   

        session = Session.getDefaultInstance(props, this);   
    }   

    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(sender));   
        message.setSubject(subject);   
        message.setDataHandler(handler);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){

        }
    }   

    public class ByteArrayDataSource implements DataSource {   
        private byte[] data;   
        private String type;   

        public ByteArrayDataSource(byte[] data, String type) {   
            super();   
            this.data = data;   
            this.type = type;   
        }   

        public ByteArrayDataSource(byte[] data) {   
            super();   
            this.data = data;   
        }   

        public void setType(String type) {   
            this.type = type;   
        }   

        public String getContentType() {   
            if (type == null)   
                return "application/octet-stream";   
            else  
                return type;   
        }   

        public InputStream getInputStream() throws IOException {   
            return new ByteArrayInputStream(data);   
        }   

        public String getName() {   
            return "ByteArrayDataSource";   
        }   

        public OutputStream getOutputStream() throws IOException {   
            throw new IOException("Not Supported");   
        }   
    }   
}  



answered Dec 4, 2018 by Daisy
• 8,120 points

Related Questions In Java

0 votes
1 answer

To use JavaMail API for sending mails in Android without using the default/built-in App

ADD 3 jars found in the following ...READ MORE

answered Jun 6, 2018 in Java by sridhar
• 160 points
1,243 views
0 votes
1 answer

What are the Foreign key constraints in Android using SQLite

You can use, Foreign key constraints with ...READ MORE

answered Aug 24, 2018 in Java by geek.erkami
• 2,680 points
1,531 views
0 votes
1 answer

How can we upload the files using JSP/ Servlets in Java?

<form action="upload" method="post" enctype="multipart/form-data"> ...READ MORE

answered Jun 8, 2018 in Java by Sushmita
• 6,910 points
712 views
0 votes
1 answer

How to call a method after a delay in Android using Java?

final Handler handler = new Handler(); handler.postDelayed(new Runnable() ...READ MORE

answered Jun 11, 2018 in Java by Akrati
• 3,190 points
5,065 views
0 votes
1 answer

How can we get the current location in Android?

First you need to define a LocationListener to handle ...READ MORE

answered Sep 25, 2018 in Java by Parth
• 4,630 points
734 views
0 votes
1 answer

Can't find class CognitoUserPoolsSignInProvider: Issue with Sign In integration

CognitoUserPoolsSignInProvider is ditributed as part of aws-android-sdk-auth-userpools library. Please import ...READ MORE

answered Sep 28, 2018 in AWS by Priyaj
• 58,090 points
660 views
0 votes
1 answer

How to Read/Write String from a File in Android

Writing a File in android: private void writeToFile(String ...READ MORE

answered Oct 3, 2018 in Java by sharth
• 3,370 points
6,932 views
0 votes
1 answer

simple HTTP server in Java using only Java SE API

The com.sun.net.httpserver solution is not portable across JREs. Its ...READ MORE

answered Jan 4, 2019 in Java by Daisy
• 8,120 points
2,163 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,220 points
3,139 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP