Skip to content

Instantly share code, notes, and snippets.

@kishandonga
Created May 3, 2023 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kishandonga/232d32cb764643adb35784398fdcb737 to your computer and use it in GitHub Desktop.
Save kishandonga/232d32cb764643adb35784398fdcb737 to your computer and use it in GitHub Desktop.
To Send Email Using Intent
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Patterns;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
public final class IntentEmail {
private final Context context;
private final Set<String> to = new LinkedHashSet<>();
private final Set<String> cc = new LinkedHashSet<>();
private final Set<String> bcc = new LinkedHashSet<>();
private String subject;
private String body;
private File attachment;
private String intentChooser;
private IntentEmail(@NonNull Context context) {
this.context = checkNotNull(context);
}
public static IntentEmail from(@NonNull Context context) {
return new IntentEmail(context);
}
private static <T> T checkNotNull(T object) {
if (object == null) {
throw new IllegalArgumentException("Argument must not be null");
}
return object;
}
static String encodeRecipient(String recipient) {
int index = recipient.lastIndexOf('@');
String localPart = recipient.substring(0, index);
String host = recipient.substring(index + 1);
return Uri.encode(localPart) + "@" + Uri.encode(host);
}
static String fixLineBreaks(String text) {
return text.replaceAll("\r\n", "\n").replace('\r', '\n').replaceAll("\n", "\r\n");
}
public IntentEmail setIntentChooser(@Nullable String intentChooser) {
this.intentChooser = intentChooser;
return this;
}
public IntentEmail attachment(@Nullable File attachment) {
this.attachment = attachment;
return this;
}
public IntentEmail to(@NonNull String to) {
checkEmail(to);
this.to.add(to);
return this;
}
public IntentEmail to(@NonNull Collection<String> to) {
checkNotNull(to);
for (String email : to) {
checkEmail(email);
}
this.to.addAll(to);
return this;
}
public IntentEmail cc(@NonNull String cc) {
checkEmail(cc);
this.cc.add(cc);
return this;
}
public IntentEmail cc(@NonNull Collection<String> cc) {
checkNotNull(cc);
for (String email : cc) {
checkEmail(email);
}
this.cc.addAll(cc);
return this;
}
public IntentEmail bcc(@NonNull String bcc) {
checkEmail(bcc);
this.bcc.add(bcc);
return this;
}
public IntentEmail bcc(@NonNull Collection<String> bcc) {
checkNotNull(bcc);
for (String email : bcc) {
checkEmail(email);
}
this.bcc.addAll(bcc);
return this;
}
public IntentEmail subject(@NonNull String subject) {
checkNotNull(subject);
checkNoLineBreaks(subject);
this.subject = subject;
return this;
}
public IntentEmail body(@NonNull String body) {
checkNotNull(body);
this.body = fixLineBreaks(body);
return this;
}
public void startActivity() {
Intent intent = build();
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if(intentChooser != null){
context.startActivity(Intent.createChooser(intent, "Send Email"));
}else {
context.startActivity(intent);
}
}
public Intent build() {
Uri mailtoUri = constructMailtoUri();
Intent intent = new Intent(Intent.ACTION_SENDTO, mailtoUri);
if(attachment != null){
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(attachment));
}
return intent;
}
private Uri constructMailtoUri() {
StringBuilder mailto = new StringBuilder(1024);
mailto.append("mailto:");
addRecipients(mailto, to);
boolean hasQueryParameters;
hasQueryParameters = addRecipientQueryParameters(mailto, "cc", cc, false);
hasQueryParameters = addRecipientQueryParameters(mailto, "bcc", bcc, hasQueryParameters);
hasQueryParameters = addQueryParameter(mailto, "subject", subject, hasQueryParameters);
addQueryParameter(mailto, "body", body, hasQueryParameters);
return Uri.parse(mailto.toString());
}
private boolean addQueryParameter(StringBuilder mailto, String field, String value, boolean hasQueryParameters) {
if (value == null) {
return hasQueryParameters;
}
mailto.append(hasQueryParameters ? '&' : '?').append(field).append('=').append(Uri.encode(value));
return true;
}
private boolean addRecipientQueryParameters(StringBuilder mailto, String field, Set<String> recipients, boolean hasQueryParameters) {
if (recipients.isEmpty()) {
return hasQueryParameters;
}
mailto.append(hasQueryParameters ? '&' : '?').append(field).append('=');
addRecipients(mailto, recipients);
return true;
}
private void addRecipients(StringBuilder mailto, Set<String> recipients) {
if (recipients.isEmpty()) {
return;
}
for (String recipient : recipients) {
mailto.append(encodeRecipient(recipient));
mailto.append(',');
}
mailto.setLength(mailto.length() - 1);
}
private void checkEmail(String email) {
checkNotNull(email);
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
throw new IllegalArgumentException("Argument is not a valid email address (according to " +
"Patterns.EMAIL_ADDRESS)");
}
}
private void checkNoLineBreaks(String text) {
boolean containsCarriageReturn = text.indexOf('\r') != -1;
boolean containsLineFeed = text.indexOf('\n') != -1;
if (containsCarriageReturn || containsLineFeed) {
throw new IllegalArgumentException("Argument must not contain line breaks");
}
}
}
@kishandonga
Copy link
Author

kishandonga commented May 3, 2023

Usage:

try {
            IntentEmail.from(context)
                    .to("abcd@gmail.com")
                    .subject("Subject")
                    .body("Enter Your Body Here")
                    .setIntentChooser("Send Email")
                    .startActivity();
        } catch (Exception e) {
            Logger.e(e);
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment