Tung Duong
Tung Duong

Reputation: 1166

How to send email from Android by javax.mail with SMTP

I'm making an app have feature send email from app by SMTP protocol. I want to make it send email in background from app not like use Intent to send by other mail app. I search on Google have some suggest to do with javax.mail.

I have SMTP server with info: host, port, username, password.

How can I use javax.mail to send email via SMTP with html inside to recipient/recipients and email have files attached too.

Thanks

Upvotes: 1

Views: 223

Answers (1)

shimatai
shimatai

Reputation: 1808

If you want to use javax.mail to send e-mail. You can use the following helper class to send e-mails. No matter if it's sent by a background service of if it's sent by an AsyncTask. Take a look at the configuration part in the class below.

package com.company.mail.util;

import java.util.Properties;

import javax.activation.DataHandler;
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 org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

public class Mail {
    public static final String EMAIL_LIST_SEPARATOR = ",";

    public boolean sendMail(String[] toEmails, String subject, String msg, boolean isHTML, String charSet, String filename, byte[] attachment) {
    if (toEmails == null || (toEmails != null && toEmails.length == 0))  return false;

    String name = "My Company Name";
    String username = "[email protected]"; 
    String password = "<My Password>"; 
    String host = "smtp.company.com";
    Integer port = 465;
    String from = "[email protected]";

    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.socketFactory.port", port.toString());
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", port.toString());

    final String fUsername = username;
    final String fPassword = password;
    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fUsername, fPassword);
        }
    });
    //mailSession.setDebug(true);

    String recipients = ArrayUtils.toString(toEmails, "");
    Message message = new MimeMessage(mailSession);
    try {
        message.setFrom(new InternetAddress(from, name));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(from, name) });
        message.setSubject(subject);
        message.setContent(msg, isHTML ? "text/html" : "text/plain");

        if (toEmails != null) {
            for (String recipient : toEmails) {
                if (recipient != null && !"".equals(recipient)) {
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                }
            }

            if (attachment != null) {
                MimeBodyPart messagePart = new MimeBodyPart();
                if (isHTML)
                    messagePart.setContent(msg, "text/html");
                else
                    messagePart.setText(msg);

                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.setDataHandler(new DataHandler(attachment, "application/octet-stream"));
                attachmentPart.setFileName(filename);

                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messagePart);
                multipart.addBodyPart(attachmentPart);

                message.setContent(multipart);
            }

            Transport.send(message);
            Log.i(" [Mail] Recipient " + name + " <" + username + "> sent e-mail with subject " + subject + " to recipient(s): " + recipients);

            return true;
        }
    } catch (Exception e) {
        Log.e(" [Mail] Error sending " + toEmails.length  + " e-mail(s) with subject '" + subject + "' to recipient(s) (" + recipients + "): " + e.getMessage());
    }

    return false;
    }
}

You can send e-mail calling the method mail.sendMail(...), for example:

Mail mail = new Mail();
mail.sendMail(new String[] { "[email protected]", "[email protected]" }, "Subject of my e-mail", "This is a message in <b>HTML</b> with <i>italics</i>.", true, "UTF-8", null, null);

This class also supports to send an attachment to the mail, so you pass the file's name and an array of bytes as two last arguments.

Hope that this Java class helps you.

Upvotes: 1

Related Questions