android smtp with attachment of db file - android

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";

Related

Error sending an email: Provider com.sun.mail.imap.IMAPProvider not found

I'm using javamail to send html emails with a gmail account. It works good in an App on my Android Emulator but when I install my app on an Android 9 device and I try to send an email, I get this error:
d.b.o.: Provider com.sun.mail.imap.IMAPProvider not found
This is the class I use:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import androidx.core.text.HtmlCompat;
import java.util.ArrayList;
import java.util.Properties;
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 SendHTMLEmail {
public static boolean SendEmail(String dst, String subject, String body) {
final String cemail;
final String cpasswd;
cemail= "mygmail#gmail.com";
cpasswd= "mypassword";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.googlemail.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");
try {
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(cemail, cpasswd);
}
});
if (session != null) {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(cemail));
message.setSubject(subject);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dst));
message.setContent(body, "text/html; charset=utf-8");
Transport.send(message);
return true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("EMAIL", e.getMessage());
}
return false;
}
}
After some test and changes I've found the error:
java.lang.ClassNotFoundException: com.sun.mail.imap.IMAPProvider
Caused by: java.lang.ClassNotFoundException: com.sun.mail.pop3.POP3Provider
And the problem was ProGuard rules. It could be solved with this:
https://stackoverflow.com/a/57431949/1616700

How to add image attachments from sdcard in email app using javamail API

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);

Email Without Intent

I want to send an email in my android application without using intent, as in i want it to be automatic. The email does not get sent to the recipient. I've looked at all the tutorials I could find, I still cant fix the problem. I added the three jar files.I added
<uses-permission android:name="android.permission.INTERNET" />
to my manifest, I changed the setting for my gmail to allow less secure logins. I dont get any errors in logcat and I've been following this method. Sending Email in Android using JavaMail API without using the default/built-in app
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 com.example.hoda.myapplication.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
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;
}
});
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button) this.findViewById(R.id.mybtn);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "button does something", Toast.LENGTH_SHORT).show();
try {
GMailSender sender = new GMailSender("email-sender#gmail.com", "password");
sender.sendMail("This is Subject",
"This is Body",
"email-sender#gmail.com",
"email-receiver#yahoo.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
private class AsyncTaskSendMail extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String host="server142.web-hosting.com";//change accordingly
final String user="*****#something.com";//change accordingly
final String password="*****";//change accordingly
String to="*****#something.com";//change accordingly
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("SAIM TEST MAIL");
message.setText("This is simple program of sending email using JavaMail API");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
} catch (MessagingException e) {e.printStackTrace();}
return "";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
Then execute whenever you want like this
new AsyncTaskSendMail().execute("Sending Email");//Passing Dummy Parameter
I still don't know what exactly the problem was with my solution but changing it to this fixed it for me!
https://github.com/steveholt55/JavaMail-API-Android
For anyone's future reference, someone that looked at my code said the transport is getting disconnected but not sure how to fix that.

sending image in email does not work

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

Send Email in Service (without prompting user)

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.

Categories

Resources