is it possible that I send email in background using service.. like in service I use Intent with ACTION_SENDTO with Uri data mailto:recipient_email and it get sent in the background without any user intervention .. or through default email app without prompting the user ...
The best solution is using the Gmail account to send the email.
Generally speaking:
download mail.jar and activation.jar for android https://code.google.com/p/javamail-android/
Connect to GMail to get the OAuth token
Send the email
here's the code
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;
public class GMailSender {
private Session session;
private String token;
public String getToken() {
return token;
}
public GMailSender(Activity ctx) {
super();
initToken(ctx);
}
public void initToken(Activity ctx) {
AccountManager am = AccountManager.get(ctx);
Account[] accounts = am.getAccountsByType("com.google");
for (Account account : accounts) {
Log.d("getToken", "account="+account);
}
Account me = accounts[0]; //You need to get a google account on the device, it changes if you have more than one
am.getAuthToken(me, "oauth2:https://mail.google.com/", null, ctx, new AccountManagerCallback<Bundle>(){
#Override
public void run(AccountManagerFuture<Bundle> result){
try{
Bundle bundle = result.getResult();
token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.d("initToken callback", "token="+token);
} catch (Exception e){
Log.d("test", e.getMessage());
}
}
}, null);
Log.d("getToken", "token="+token);
}
public SMTPTransport connectToSmtp(String host, int port, String userEmail,
String oauthToken, boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "false");
session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
/* enable if you use this code on an Activity (just for test) or use the AsyncTask
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
*/
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1",
userEmail, oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);
return transport;
}
public synchronized void sendMail(String subject, String body, String user,
String oauthToken, String recipients) {
try {
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587,
user, oauthToken, true);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(user));
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));
smtpTransport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
Log.d("test", e.getMessage(), e);
}
}
}
this code was originally posted here Javamail api in android using XOauth.
Please note to get the OAuth token you need an Activity and you have to ask the user which account to use. The token should be retrieved during the OnCreate phase and saved in the preferences. See also How to get the Android device's primary e-mail address
Alternatively you can use mail.jar but you have to ask the user for their username and password.
Related
I'm new to android programming and Android Studio, I'm developing a simple android application that can send a email with attachment. I already can send email but with the attachment part I'm having troubles. When I add the mimebodypart for the attachment I can't receive any emails now. Here's my code
SimpleMail.java
package com.team8.javamail2;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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;
/**
* Created by VEN on 1/27/2019.
*/
public class SimpleMail {
/**CHANGE ACCORDINGLY**/
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER = "unvrsx#gmail.com";
private static final String SMTP_AUTH_PWD = "XXXXXXXXXX";
private static Message message;
private File file ;
private Context context;
public static void sendEmail(String to, String subject, String msg){
// Recipient's email ID needs to be mentioned.
// Sender's email ID needs to be mentioned
String from = "unvrsx#gmail.com"; //from
final String username = SMTP_AUTH_USER;
final String password = SMTP_AUTH_PWD;
// Assuming you are sending email through relay.jangosmtp.net
String host = SMTP_HOST_NAME;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setContent(msg, "text/html");
// Create a multipar message
// Set text message part
// Part two is attachment
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
// Send the complete message partBidt
message.setContent(multipart);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
MainActivity.java
package com.team8.javamail2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private EditText toEmailEditText;
private EditText subjectEditText;
private EditText messageEditText;
private Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toEmailEditText = (EditText) findViewById(R.id.editTextEmail);
subjectEditText = (EditText) findViewById(R.id.editTextSubject);
messageEditText = (EditText) findViewById(R.id.editTextMessage);
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String to = toEmailEditText.getText().toString().trim();
String subject = subjectEditText.getText().toString();
String message = messageEditText.getText().toString();
if(to.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a recipient email", Toast.LENGTH_LONG).show();
}else if(subject.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a Subject", Toast.LENGTH_LONG).show();
}else if(message.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a message", Toast.LENGTH_LONG).show();
}else {
//everything is filled out
//send email
new SimpleMail().sendEmail(to, subject, message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.team8.javamail2">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I don't know if something around here cause the problem
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
I am using this code (given below) to send image through email from my android application, the email is received but it does not have the image. Please tell what is issue in my code?
Received Mail:
email body
Code:
package com.example.appdeveloper.appname;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import java.io.File;
import java.util.Properties;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailHandler extends AsyncTask<Void, Void, Boolean> {
private static String to = "reciever#example.com";
private static String from = "sender#example.com";
private static String subject = "Subject";
private static String sender = "Android App";
private static String mail;
private static String username = "sender";
private static String password = "password";
EmailHandler(Context context) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/test.png";
mail ="<!DOCTYPE html><html><body><img src="+path+"></body></html>";
}
#Override
protected Boolean doInBackground(Void... nothing) {
try {
Authenticator auth = new EmailAutherticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.user", username);
properties.setProperty("mail.smtp.password", password);
Session session = Session.getDefaultInstance(properties,auth);
MimeMessage message = new MimeMessage(session);
message.setSubject(subject);
message.setContent(mail, "text/html; charset=utf-8");
Address address = new InternetAddress(from,sender);
message.setFrom(address);
InternetAddress ad[] = new InternetAddress[2];
ad[0] = new InternetAddress(to);
ad[1] = new InternetAddress(from);
message.addRecipients( Message.RecipientType.TO, ad );
Transport.send(message);
return true;
}
catch(Exception exp) {
exp.printStackTrace();
return false;
}
}
}
class EmailAutherticator extends Authenticator {
private String username = "sender";
private String password = "password";
public EmailAutherticator() {
super();
}
public EmailAutherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
So your Email comes across with body like this (kinda):
<!DOCTYPE html><html><body><img src="\myPhone\DCIM\image.png"></body></html>
Your email won't be able to get to that location unless you read email on your phone.
EDIT 1
You can attach extra data to your intent by using Intent.EXTRA_STREAM as outlined in Android documentation here
i am trying to create a android smtp app, in which i want to access the internal storage (Where a .db or .db.crypt file is stored) and from there i want to get that file and sent it via email.
below is my code,where everything is working fine. i am able to get that file and send it. but suppose my original file name is "file1.db" but after sending it through smtp it receives as "file1" which is just a file.
any one having idea? plz tell me how can i send that db file???
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
//Class is extending AsyncTask because this class is going to perform a networking operation
public class SendMail extends AsyncTask<Void,Void,Void> {
//Declaring Variables
private Context context;
private Session session;
//Information to send email
private String email;
private String subject;
private String message;
//Progressdialog to show while sending email
private ProgressDialog progressDialog;
//Class Constructor
public SendMail(Context context, String email, String subject, String message){
//Initializing variables
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
progressDialog = ProgressDialog.show(context,"Sending message","Please wait...",false,false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing a success message
Toast.makeText(context,"Message Sent",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Config.EMAIL, Config.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
//Setting sender address
mm.setFrom(new InternetAddress(Config.EMAIL));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(message);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+File.separator+"PasswordSafe.db"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
messageBodyPart.setFileName("file1");
multipart.addBodyPart(messageBodyPart);
mm.setContent(multipart);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}}
This will do the trick for you..
String fileName = name + " yourFile"+".db";
I am developing an app in which I want to send mail programmatically using Gmail credentials, I know how to access device mail id and token using AccountManager. Please suggest me how to send mail using credentials with some code or tutorial. I am new to Android. Please help me thanks in advance..
After very hard work now i am able to login to Google using Oauth 2. now i am sharing here coz many questions are unanswered here. Below steps are require to login to Google.
1- Select a account from your device using
public static AccountManager accountManager;
accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
2- Get a Token from selected account using
private void onAccountSelected(final Account account) {
accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
useToken(account, token);
} catch (OperationCanceledException e) {
onAccessDenied();
} catch (Exception e) {
handleException(e);
}
}
}, null);
}
3- now Authenticate the Token using user account and Token. you will be able to login to google.
Note: After sometime token get unauthorized to login so you need to invalidate your token.
4- for re login you have to invalidate your token using
accountManager.invalidateAuthToken("com.google", token);
5- after invalidate you have to get a new token using
String newToken = AccountManager.get(this).getAuthToken(new Account(account, "com.google"),
AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
6- in your AndroidManifest.xml add below uses permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
Thats all you require, now enjoy
fist you download activation.jar,mail.jar,additionnal.jar and add to built to your project
And code r following
---------Create GMailSender.class
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
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 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){
e.printStackTrace();
}
}
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");
}
}
}
2-Create JSSEProvider.class
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;
}
});
}
}
3-use This code in to your Activity button click etc..
try {
GMailSender sender = new GMailSender("sender gmail ID", "password");
sender.sendMail("This is Subject",
"This is Body",
"receiverID",
"receiverID");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
Source: https://stackoverflow.com/a/2033124/865900 (credit where credit is due)
This question already has answers here:
Sending Email in Android using JavaMail API without using the default/built-in app
(25 answers)
Closed 9 years ago.
I am making an app that allows the user to take a picture and send it automatically via email to the email he chooses. So far I was able to take a picture and store in the SD card. Now I only need functions that get the picture from the folder (/sdcard/Pictures/PhotoSender/) and send automatically to the e-mail the user has requested. How can I do this?
I have the picture in that folder. I just need some functions to generate the e-mail, put the picture (.jpg) as an attachment and send (all this on background). When the e-mail gets totally sent, a toast should pop up saying "Upload Done". Meanwhile the user should be free to take more pictures, so the uploading requests should be put on a queue. The user shouldn't login with his e-mail account to send. If needed, I can create an e-mail account for my app to be the "sender". Please help me!
Below is a complete class that supports sending emails with attachments in Android
And here is a utility function to send mail with attachment where the attachment in your case is simply the picture(s) file complete path
public static boolean sendEmail(String to, String from, String subject,
String message,String[] attachements) throws Exception {
Mail mail = new Mail();
if (subject != null && subject.length() > 0) {
mail.setSubject(subject);
} else {
mail.setSubject("Subject");
}
if (message != null && message.length() > 0) {
mail.setBody(message);
} else {
mail.setBody("Message");
}
mail.setTo(new String[] {to});
if (attachements != null) {
for (String attachement : attachements) {
mail.addAttachment(attachement);
}
}
return mail.send();
}
Here is the complete Mail class that is used in the above function
import java.io.File;
import java.util.Date;
import java.util.Properties;
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.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;
public class Mail 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 multipart;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String[] getTo() {
return to;
}
public void setTo(String[] to) {
this.to = to;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Multipart getMultipart() {
return multipart;
}
public void setMultipart(Multipart multipart) {
this.multipart = multipart;
}
public Mail() {
host = "smtp.googlemail.com"; // default smtp server
port = "465"; // default smtp port
sport = "465"; // default socketfactory port
user = ""; // username
password = ""; // password
from = ""; // email sent from
subject = ""; // email subject
body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
multipart = 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/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
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 Mail(String user, String pass) {
this();
this.user = user;
password = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if (!user.equals("") && !password.equals("") && to.length > 0
&& !from.equals("") && !subject.equals("") && !body.equals("")) {
Session session = Session.getInstance(props, this);
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());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
// send email
Transport.send(msg);
return true;
} else {
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(new File(filename).getName());
multipart.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;
}
// the getters and setters
public String getBody() {
return body;
}
public void setBody(String _body) {
this.body = _body;
}
}
Note:
You will need activiation.jar and mail.jar in your classpath i.e. JavaMail API
The code should run from AsynchTask or dedicated Thread
Assuming your device of emualtor has a email application, the below code can be used to sent a mail. You can use any email application installed on your emualtor or device be it yahoomail or google. If you want tp run the same in background use a service.
Intent i = new Intent(Intent.ACTION_SEND);
//i.setType("text/plain"); //use this line for testing in the emulator
i.setType("message/rfc822") ; // use from live device
i.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");//sending email via gmail
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");
i.putExtra(Intent.EXTRA_TEXT,"body goes here");
startActivity(i);