Sending Email in Android using JavaMail API without using the default/built-in app
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");
}
}
}
JSSEProvider.java:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
ADD 3 jars found in the following link to your Android Project
- mail.jar
- activation.jar
- additional.jar
Click here - How to add External Jars
And don't forget to add this line in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Just click below link to change account access for less secure apps
https://www.google.com/settings/security/lesssecureapps
Run the project and check your recipient mail account for the mail.
Cheers!
P.S. And don't forget that you cannot do network operation from any Activity in android.
Hence it is recommended to use AsyncTask
or IntentService
to avoid network on main thread exception.
Jar files: https://code.google.com/archive/p/javamail-android/
Sending Email in Android using JavaMail API without using the default/built-in app only works on emulator?
I had the same issue on my android version 4.0.3.
Changing the min sdk version to 7 did the trick.
<uses-sdk android:minSdkVersion="7" />
Sending an e-mail without using the built-in app
Fix all these common mistakes, including getting rid of the Authenticator.
Get rid of the call to super() in your constructor, you don't need it.
Also, get rid of the ByteArrayDataSource class. You don't need your own since it comes with JavaMail. Plus, your program isn't even using it.
If it still doesn't work, update your post with your new code and new failure details.
How to send email using user's email ID from within the app (Without Intent)
Please, take a look at the Gmail API Android Quickstart guide. You'll be able to get the account credentials from Google Play Services and authenticate your user with OAuth2 by prompting an account selection
Sending email without user Interaction - Android Studio
it's not the answer of your question , but i think it could be helpful
check this out https://mandrillapp.com/api/docs/
i use mandrill api to send email in my application
first of all you create account in mandrill site then you fill data that email should contain in json format like what you see in this link https://mandrillapp.com/api/docs/messages.html#method=send
and after that excute HTTP POST requests that contain your json to this uri : https://mandrillapp.com/api/1.0/messages/send.json
implementation
//**********Method to send email
public void sendEmail(){
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
Toast.makeText(MainActivity.this,
"Your message was sent successfully.",
Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... params) {
String respond = POST(
URL,
makeMandrillRequest(fromEmail.getText()
.toString(), toEmail.getText()
.toString(), name.getText()
.toString(), text.getText()
.toString(), htmlText.getText()
.toString()));
Log.d("respond is ", respond);
return null;
}
}.execute();
}
//*********method to post json to uri
public String POST(String url , JSONObject jsonObject) {
InputStream inputStream = null;
String result = "";
try {
Log.d("internet json ", "In post Method");
// 1. create HttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. convert JSONObject to JSON to String
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
// 4. set httpPost Entity
httpPost.setEntity(se);
// 5. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 6. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 7. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 8. convert inputstream to string
if(inputStream != null){
result = convertStreamToString(inputStream);
}else{
result = "Did not work!";
Log.d("json", "Did not work!" );
}
} catch (Exception e) {
Log.d("InputStream", e.toString());
}
// 9. return result
return result;
}
//*****************TO create email json
private JSONObject makeMandrillRequest(String from, String to, String name,
String text, String htmlText) {
JSONObject jsonObject = new JSONObject();
JSONObject messageObj = new JSONObject();
JSONArray toObjArray = new JSONArray();
JSONArray imageObjArray = new JSONArray();
JSONObject imageObjects = new JSONObject();
JSONObject toObjects = new JSONObject();
try {
jsonObject.put("key", "********************");
messageObj.put("html", htmlText);
messageObj.put("text", text);
messageObj.put("subject", "testSubject");
messageObj.put("from_email", from);
messageObj.put("from_name", name);
messageObj.put("track_opens", true);
messageObj.put("tarck_clicks", true);
messageObj.put("auto_text", true);
messageObj.put("url_strip_qs", true);
messageObj.put("preserve_recipients", true);
toObjects.put("email", to);
toObjects.put("name", name);
toObjects.put("type", "to");
toObjArray.put(toObjects);
messageObj.put("to", toObjArray);
if (encodedImage != null) {
imageObjects.put("type", "image/png");
imageObjects.put("name", "IMAGE");
imageObjects.put("content", encodedImage);
imageObjArray.put(imageObjects);
messageObj.put("images", imageObjArray);
}
jsonObject.put("message", messageObj);
jsonObject.put("async", false);
Log.d("Json object is ", " " + jsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
also check this library , it could make it easier to implement .
Related Topics
How to Style the Progressbar Component in Javafx
Android - Start Service on Boot
Technically What Is the Main Difference Between Oracle Jdk and Openjdk
What Does "Could Not Find or Load Main Class" Mean
Loading Resources Like Images While Running Project Distributed as Jar Archive
Difference Between ≪? Super T≫ and ≪? Extends T≫ in Java
How to Get the Insert Id in Jdbc
:: (Double Colon) Operator in Java 8
Find Div Element by Multiple Class Names
Firebaselistadapter Not Pushing Individual Items For Chat App - Firebase-Ui 3.1
Why Retrieving Google Directions For Android Using Kml Data Is Not Working Anymore
Gradle Finds Wrong Java_Home Even Though It's Correctly Set
Connect Java to a MySQL Database
"Implements Runnable" VS "Extends Thread" in Java
How to Handle Infinite Loop Caused by Invalid Input (Inputmismatchexception) Using Scanner