Embedd inline images using JAVA Mail in android? - android

I need to send email using JAVA Mail with inline images not as an attachment. I used the third party JAR files and modified some code but did not get any images in my email. Here is my code.
GMailSender.java
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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;
public class GMailSender extends javax.mail.Authenticator
{
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
private Transport transport;
private static final int SMTP_HOST_PORT = 465;
static
{
Security.addProvider(new com.power.calculator.gal.JSSEProvider());
}
public GMailSender(String user, String password) throws Exception
{
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);
session.setDebug(true);
transport = session.getTransport();
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients, String imagePath) throws Exception
{
try
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/html"));
message.setSubject(subject);
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(sender));
message.setDataHandler(handler);
message.setSender(new InternetAddress(sender));
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File(imagePath));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("1.png");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setHeader("Content-ID","<vogue>");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String htmlText = body;
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
transport.connect(mailhost, SMTP_HOST_PORT, user, password);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
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;
#SuppressWarnings("serial")
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;
}
});
}
}
My Activity Class:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class PowerCalculatorActivity extends Activity implements OnClickListener, Runnable
{
protected static final String TAG = "TAG";
private static final String ERROR = "Error";
private static final String OK = "OK";
private static final int ZERO = 0;
private static final int ONE = 1;
private static final int TWO = 2;
private static final int THREE = 3;
private static final String MESSAGEONE = " Please enter valid email address ";
private static final String MESSAGETWO = "Please enter valid name and email address";
private static String mErrorMessages;
private EditText mName, mEmail;
private Button mSubmit;
private Dialog showErrorDialog, showProgressDialog;
private Handler mHandler = new Handler()
{
public void handleMessage(Message nMessage)
{
switch (nMessage.what)
{
case ZERO:
showProgressDialog.dismiss();
Intent mHelpIntent = new Intent(PowerCalculatorActivity.this, ByOptions.class);
mHelpIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(mHelpIntent);
PowerCalculatorActivity.this.finish();
break;
case ONE:
showProgressDialog.dismiss();
showErrorDialog(ERROR, MESSAGEONE, OK);
break;
case TWO:
showProgressDialog.dismiss();
showErrorDialog(ERROR, MESSAGETWO, OK);
break;
case THREE:
showProgressDialog.dismiss();
showErrorDialog(ERROR, mErrorMessages, OK);
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.login);
//Initialize view
mName = (EditText)findViewById(R.id.NameText);
mEmail = (EditText)findViewById(R.id.EmailText);
mSubmit = (Button)findViewById(R.id.Submit);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View nView)
{
switch(nView.getId())
{
case R.id.Submit:
showCustomProgressDialog();
Thread mLoadingThread = new Thread(this);
mLoadingThread.start();
break;
}
}
#Override
public void run()
{
if(mName.getText().toString().trim().length() > 0 && mEmail.getText().toString().trim().length() > 0)
{
String mSenderEmail = mEmail.getText().toString().trim();
boolean mValidEMail = isEmailValid(mSenderEmail);
if(mValidEMail)
{
String mEmailSubject = getResources().getString(R.string.emailsubject);
String mRecipients = getResources().getString(R.string.clientemail);
String mMyEmail = getResources().getString(R.string.emailaddress);
String mMessage = "Name: " + mName.getText().toString().trim() + "<br>" + "Email: " + mEmail.getText().toString().trim()
+ "<br><br>" + "<img src=\"cid:vogue\">";
String mImagePath = "/sdcard/1.png";
String mPassword = getResources().getString(R.string.emailpassword);
try
{
GMailSender mSender = new GMailSender(mMyEmail, mPassword);
mSender.sendMail(mEmailSubject,
mMessage,
mSenderEmail,
mRecipients, mImagePath);
}
catch(Exception e)
{
mErrorMessages = e.getMessage();
Log.e(TAG, e.getMessage(), e);
Message mMessageSend = new Message();
mMessageSend.what = THREE;
mHandler.sendMessage(mMessageSend);
}
Message mMessageSend = new Message();
mMessageSend.what = ZERO;//Success
mHandler.sendMessage(mMessageSend);
}
else
{
Message mMessageSend = new Message();
mMessageSend.what = ONE;//Fail
mHandler.sendMessage(mMessageSend);
}
}
else
{
Message mMessageSend = new Message();
mMessageSend.what = TWO;//Fail
mHandler.sendMessage(mMessageSend);
}
}
/**
* This method send data to the client using JAVA Mail
*/
private void showCustomProgressDialog()
{
showProgressDialog = new Dialog(PowerCalculatorActivity.this, R.style.ProgressDialog);
showProgressDialog.setContentView(R.layout.customloadingprogress);
showProgressDialog.getWindow().setGravity(Gravity.CENTER);
showProgressDialog.setCancelable(true);
showProgressDialog.show();
}
/**
* This method is used for checking valid email id format.
* #param email
* #return boolean true for valid and false for invalid
*/
public static boolean isEmailValid(String nComingEmail)
{
boolean isValid = false;
String mExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence mInputEmail = nComingEmail;
Pattern mPattern = Pattern.compile(mExpression, Pattern.CASE_INSENSITIVE);
Matcher mMatcher = mPattern.matcher(mInputEmail);
if (mMatcher.matches())
{
isValid = true;
}
return isValid;
}
/**
* This method shows error message when entered information is wrong
* #param nTitle
* #param nMessage
* #param nPosButton
*/
private void showErrorDialog(String nTitle, String nMessage, String nPosButton)
{
showErrorDialog = new Dialog(this);
CustomDialog.Builder customBuilder = new CustomDialog.Builder(this);
customBuilder.setTitle(nTitle);
customBuilder.setMessage(nMessage);
customBuilder.setPositiveButton(nPosButton, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
showErrorDialog.dismiss();
}
});
showErrorDialog = customBuilder.create();
showErrorDialog.setCancelable(true);
showErrorDialog.show();
}
/**
* This method create option menu
* #param menu
* #return true if menu created successfully
*/
#Override
public boolean onCreateOptionsMenu(Menu nMenu)
{
MenuInflater mInflater = getMenuInflater();
mInflater.inflate(R.menu.menubar, nMenu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//Handle item selection
switch (item.getItemId())
{
case R.id.help:
Intent mHelpIntent = new Intent(PowerCalculatorActivity.this, HelpScreen.class);
mHelpIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(mHelpIntent);
return true;
case R.id.contactus:
Intent mContactUsIntent = new Intent(PowerCalculatorActivity.this, ContactUs.class);
mContactUsIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(mContactUsIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* This method catches the back key event and finish the current activity
* #param keyevent
* #return boolean true for valid catch
*/
#Override
public boolean onKeyDown(int mKeyCode, KeyEvent mKeyEvent)
{
if ((!(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
&& mKeyCode == KeyEvent.KEYCODE_BACK && mKeyEvent.getRepeatCount() == 0))
{
onBackPressed();
}
return super.onKeyDown(mKeyCode, mKeyEvent);
}
public void onBackPressed()
{
finish();
}
}
External JARS are available here: Sending Email in Android using JavaMail API without using the default/built-in app
Complete Solution: I have edited all my files.
Thanks,
AndroidVogue

You will need another part that contains the HTML referring to your image, check out this small example:
public class GMail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "...#gmail.com";
private static final String SMTP_AUTH_PWD = "pwd";
public static void main(String[] args) throws Exception{
new GMail().send();
}
public void send() throws Exception{
// prepare session & transport object
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", SMTP_HOST_NAME);
props.put("mail.smtps.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
// prepare messge
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing embedded image");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("...#googlemail.com"));
// create multipart
Multipart multipart = new MimeMultipart();
// create bodypart with image and set content-id
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File("/Users/Tim/Desktop/image.png"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("image.png");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setHeader("Content-ID","<vogue>");
multipart.addBodyPart(messageBodyPart);
// create bodypart with html content and reference to the content-id
messageBodyPart = new MimeBodyPart();
String htmlText = "<img src=\"cid:vogue\">";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
// add multipart to message
message.setContent(multipart);
// connect & send message
transport.connect
(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

Related

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.

Android send image from javamail api

i am stuck in a project trying to send an image in the body of the mail that i am sending in my app, someone knows how can i do that?
here is the part of the code that i send the mail:
try {
String[] recipients = {editText.getText().toString()};
SendEmailAsyncTask email = new SendEmailAsyncTask();
email.m = new Mail(Base64Decoder.decoderBase64(ajudaquimail), Base64Decoder.decoderBase64(ajudaquipass));
email.m.set_from("ajudaquisuporte#gmail.com");
email.m.setBody("Seu amigo " + userName + " Te convida para participar do Aplicativo Ajudaqui, verifique também o grupo " + groupName + " para que possam compartilhar de suas ajudas: \n\n LINK PARA O APP:\n " + link);
email.m.get_multipart();
email.m.set_to(recipients);
email.m.set_subject("AJUDAQUI - CONVITE");
email.execute();
Toast.makeText(getApplicationContext(), "Mensagem enviada", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Falha ao enviar mensagem, Verifique o email digitado", Toast.LENGTH_SHORT).show();
}
here is my Mail object:
package studio.brunocasamassa.ajudaquioficial.helper;
/**
* Created by bruno on 31/07/2017.
*/
import android.content.res.AssetManager;
import android.view.View;
import java.io.InputStream;
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;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* Created by brandonjenniges on 11/6/15.
*/
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private View _view;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_view = null;
_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();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if (!_user.equals("") && !_pass.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);
AssetManager am = getApplicationContext().getAssets();
InputStream is = null;
// HERE I AM TRYING TO GET MY IMAGE FROM ASSETS AND PUTTING IN THE DATA SOURCE
//BUT IS WRONG AND HERE IS MY DOUBT
DataSource source = new FileDataSource("invite.jpg");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("invite.jpg");
_multipart.addBodyPart(messageBodyPart);
msg.setHeader("X-Priority", "1");
// 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(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
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;
}
public String get_user() {
return _user;
}
public void set_user(String _user) {
this._user = _user;
}
public String get_pass() {
return _pass;
}
public void set_pass(String _pass) {
this._pass = _pass;
}
public String[] get_to() {
return _to;
}
public void set_to(String[] _to) {
this._to = _to;
}
public String get_from() {
return _from;
}
public void set_from(String _from) {
this._from = _from;
}
public String get_port() {
return _port;
}
public void set_port(String _port) {
this._port = _port;
}
public String get_sport() {
return _sport;
}
public void set_sport(String _sport) {
this._sport = _sport;
}
public String get_host() {
return _host;
}
public void set_host(String _host) {
this._host = _host;
}
public String get_subject() {
return _subject;
}
public void set_subject(String _subject) {
this._subject = _subject;
}
public boolean is_auth() {
return _auth;
}
public void set_auth(boolean _auth) {
this._auth = _auth;
}
public boolean is_debuggable() {
return _debuggable;
}
public void set_debuggable(boolean _debuggable) {
this._debuggable = _debuggable;
}
public Multipart get_multipart() {
return _multipart;
}
public void set_multipart(Multipart _multipart) {
this._multipart = _multipart;
}
public View get_view() {
return _view;
}
public void set_view(View _view) {
this._view = _view;
}
}
if someone knows how to solve that, it will be very grateful
tks
First, fix all these common JavaMail mistakes, then update your original post with the new code.
You have an addAttachment method, but you're never calling it. Did you copy this code from someone else without understanding how it works?
The code you have is using the same MimeBodyPart (messageBodyPart) for both the main text and the image attachment; you need one for each.
And if you really want the image to be "in the body" of the message, you need to create a multipart/related message with a text/html main body part and a related image/jpeg part containing the image that's referenced from the html part using cid: URL references.

Java mail API not working in android

I added the three jar files to java build path,added Internet uses permission all setted good to go.! I putted a button in my main page, whenever i click on this button an intent to this java mail class to work, and the email have to send to the corresponding users. But when i click on the button It suddenly shows up that Appplication stopped working..!! One thing is that i didnt used any layout for this java mail class. that you will understand when you see the below code. it cause i want to send the message automatically.!! what to do.?? help me guys.?? Thank You.!!
package;
import java.util.Date;
import android.content.Intent;
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 _pass;
private String to1,to2,to3,to4,to5; // here i putted my recepients name
private String[] _to = {to1,to2,to3,to4,to5};
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject = "HELLO";
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_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();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.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(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
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;
}
// more of the getters and setters …..
}
You should post the code that calls this class (likely your Activity). There are some common problems that could cause this, like the NetworkOnMainThreadException.
I wrote some working Android mail code based on the same javax.mail code, and it works correctly. Here's the code:
submitButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
/*
* Send email in a background thread
*/
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// retrieve the configuration values from preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(theActivity);
String destinationAddress = preferences.getString("email_destination_address", theActivity.getString(R.string.default_email_destination_address));
String senderAddress = preferences.getString("email_from", theActivity.getString(R.string.default_email_sender_address));
String senderPassword = preferences.getString("email_password", theActivity.getString(R.string.default_email_sender_password));
String smtpServer = preferences.getString("email_server", theActivity.getString(R.string.default_smtp_server));
Mail m = new Mail(senderAddress, senderPassword);
String[] toArr = { destinationAddress };
m.setHost(smtpServer);
m.setTo(toArr);
m.setFrom(EMAIL_USERNAME);
m.setSubject(getString(R.string.email_subject, barcode));
m.setBody(getString(R.string.email_body));
try {
ArrayList<String> filesToSend = theAdapter.getFilenames();
for (String file : filesToSend)
{
m.addAttachment(file);
}
if (m.send()) {
Log.d(TAG, "EMAIL SENT SUCCESSFULLY");
} else {
Log.w(TAG, "EMAIL NOT SENT");
}
} catch (Exception e) {
Log.e(TAG, "Could not send email", e);
}
}
});
t.start();
Toast.makeText(getApplicationContext(), getString(R.string.email_sending), Toast.LENGTH_LONG).show();
theActivity.onBackPressed();
}
});
Note: if I were writing this code today I might use an AsyncTask instead of a Thread, but either are considered valid.
You are missing the rest of the code for getters and setters. See the comment at the bottom of your code:
// more of the getters and setters …..
You need to add the following in place of that comment:
/**
* METHOD TO SET THE "TO" STRING ARRAY
* #param toArr
*/
public void setTo(String[] toArr) {
this._to = toArr;
}
/**
* METHOD TO GET THE "TO" STRING ARRAY
* #return
*/
public String[] getTo() {
return _to;
}
/**
* METHOD TO SET THE "FROM" FIELD FOR THE MESSAGE
* #param string
*/
public void setFrom(String string) {
this._from = string;
}
/**
* METHOD TO GET THE "FROM" FIELD FOR THE MESSAGE
* #return
*/
public String getFrom() {
return _from;
}
/**
* METHOD TO SET THE MESSAGE SUBJECT
* #param string
*/
public void setSubject(String string) {
this._subject = string;
}
/**
* METHOD TO GET THE MESSAGE SUBJECT
* #return
*/
public String getSubject() {
return _subject;
}
This should work. The next obstacle you will face will be what DShaw mentions below about the NetworkOnMainThreadException, which can be fixed by either using this post to not check StrictMode, but the better option is to use AsyncTask as is discussed in this post.
[EDIT] I also had a problem with proguard! If none of the above works, try to disable proguard to see if it works then.
Hope this helps.

My JavaMail app works fine on Emulator but it is not working on my android mobile device

when i run my app on emulator it sends Email (as i expected )but when i try to run my app on device its says "There was a problem sending the email." .....
I have already added 3 jar files i-e mail.jar,additional,activational
i have already added internet permission in manifest ...
code is here
MainActivity.java
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;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
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);
Button addImage = (Button) findViewById(R.id.button1);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("XXXXXX#gmail.com", "password");
String[] toArr = {"send to #yahoo.com"};
//m.send()
m.setTo(toArr);
m.setFrom("YXY#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
Toast.makeText(getApplicationContext(), "okkk setting.", Toast.LENGTH_LONG).show();
try {
// m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "There was a problem sending the email.", Toast.LENGTH_LONG).show();
// Log.e("MailApp", "Could not send email", e);
}
}
});
}
Mail.java
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
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 Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // 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();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
// Toast.makeText(,"enter", Toast.LENGTH_LONG).show();
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(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
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;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string1) {
// TODO Auto-generated method stub
this._subject=string1;
}
// more of the getters and setters …..
}
////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I find the solution
Actually there is a api combatibilty problem
first add in onCreate method
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
then change in manifst file
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="15" />
Now its working fine on my emulator + mobile device

Using the existing gmail account and send mails

Till now I have gone through various forums and found that we have to get the token to send email. I have tried in various ways but not able to send mail to any. Can anyone please help me by sending various links related to this.
This is my Mail.java class
package com.mycomp.android.test;
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;
public class Mail extends javax.mail.Authenticator {
private Multipart attachements;
private String fromAddress = "";
private String accountEmail = "";
private String accountPassword = "";
private String smtpHost = "smtp.gmail.com";
private String smtpPort = "465"; // 465,587
private String toAddresses = "";
private String mailSubject = "";
private String mailBody = "";
public Mail() {
attachements = new MimeMultipart();
}
public Mail(String user, String pass) {
this();
accountEmail = user;
accountPassword = pass;
}
public boolean send() throws Exception {
Properties props = new Properties();
//props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", smtpPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
try {
Session session = Session.getInstance(props, this);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill message
messageBodyPart.setText(mailBody);
// add to multipart
attachements.addBodyPart(messageBodyPart);
//msg.setText(mailBody);
msg.setSubject(mailSubject);
msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddresses));
msg.setContent(attachements);
Transport transport = session.getTransport("smtps");
transport.connect(smtpHost, 465, accountEmail, accountPassword);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception e) {
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("filename");
attachements.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(accountEmail, accountPassword);
}
/**
* Gets the fromAddress.
*
* #return <tt> the fromAddress.</tt>
*/
public String getFromAddress() {
return fromAddress;
}
/**
* Sets the fromAddress.
*
* #param fromAddress <tt> the fromAddress to set.</tt>
*/
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
/**
* Gets the toAddresses.
*
* #return <tt> the toAddresses.</tt>
*/
public String getToAddresses() {
return toAddresses;
}
/**
* Sets the toAddresses.
*
* #param toAddresses <tt> the toAddresses to set.</tt>
*/
public void setToAddresses(String toAddresses) {
this.toAddresses = toAddresses;
}
/**
* Gets the mailSubject.
*
* #return <tt> the mailSubject.</tt>
*/
public String getMailSubject() {
return mailSubject;
}
/**
* Sets the mailSubject.
*
* #param mailSubject <tt> the mailSubject to set.</tt>
*/
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}
/**
* Gets the mailBody.
*
* #return <tt> the mailBody.</tt>
*/
public String getMailBody() {
return mailBody;
}
/**
* Sets the mailBody.
*
* #param mailBody <tt> the mailBody to set.</tt>
*/
public void setMailBody(String mailBody) {
this.mailBody = mailBody;
}
}
This is my MailSenderActivity.java class
package com.mycomp.android.test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Pattern;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MailSenderActivity extends Activity {
AccountManager am = AccountManager.get(this); // "this" references the current Context
Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = am.getAccountsByType("com.google");
private static final String GMAIL_EMAIL_ID = "From Email Address";
private static final String GMAIL_ACCOUNT_PASSWORD = "password";
private static final String TO_ADDRESSES = "To Email Address";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
writeFile();
final Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new MailSenderActivity.MailSender().execute();
}
});
}
private File imageFile;
private boolean writeFile() {
imageFile = new File(
getApplicationContext().getFilesDir() + "/images/",
"sample.png");
String savePath = imageFile.getAbsolutePath();
System.out.println("savePath :" + savePath + ":");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(savePath, false);
} catch (FileNotFoundException ex) {
String parentName = new File(savePath).getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if ((!(parentDir.exists())) && (parentDir.mkdirs()))
try {
fileOutputStream = new FileOutputStream(savePath, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// here i am using a png from drawable resources as attachment. You can use your own image byteArray while sending mail.
Bitmap bitmap = BitmapFactory.decodeResource(
MailSenderActivity.this.getResources(), R.drawable.english);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imgBuffer = stream.toByteArray();
boolean result = true;
try {
fileOutputStream.write(imgBuffer);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result = false;
} catch (IOException e2) {
e2.printStackTrace();
result = false;
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
result = false;
}
}
}
return result;
}
class MailSender extends AsyncTask<Void, Integer, Integer> {
ProgressDialog pd = null;
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(MailSenderActivity.this);
pd.setTitle("Uploading...");
pd.setMessage("Uploading image. Please wait...");
pd.setCancelable(false);
pd.show();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Integer doInBackground(Void... params) {
Mail m = new Mail(GMAIL_EMAIL_ID, GMAIL_ACCOUNT_PASSWORD);
String toAddresses = TO_ADDRESSES;
m.setToAddresses(toAddresses);
m.setFromAddress(GMAIL_EMAIL_ID);
m.setMailSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setMailBody("Email body.");
// try {
// ZipUtility.zipDirectory(new File("/mnt/sdcard/images"),
// new File("/mnt/sdcard/logs.zip"));
// } catch (IOException e1) {
// Log.e("MailApp", "Could not zip folder", e1);
// }
try {
String path = imageFile.getAbsolutePath();
System.out.println("sending path:" + path + ":");
m.addAttachment(path);
// m.addAttachment("/mnt/sdcard/logs.zip");
if (m.send()) {
System.out.println("Message sent");
return 1;
} else {
return 2;
}
} catch (Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return 3;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
if (result == 1)
Toast.makeText(MailSenderActivity.this,
"Email was sent successfully.", Toast.LENGTH_LONG)
.show();
else if (result == 2)
Toast.makeText(MailSenderActivity.this, "Email was not sent.",
Toast.LENGTH_LONG).show();
else if (result == 3)
Toast.makeText(MailSenderActivity.this,
"There was a problem sending the email.",
Toast.LENGTH_LONG).show();
}
}
}
If I set GMAIL_EMAIL_ID,GMAIL_ACCOUNT_PASSWORD and TO_ADDRESSES manually I am able to send message. But i have get the default GMAIL_EMAIL_ID and GMAIL_ACCOUNT_PASSWORD whisch are already in app of mobile.
You can use this to send email with attachments:
public static void sendEmail(Context context, String emailTo, String emailCC, String subject, String emailText, String type, List<String> filePaths) {
//need to "send multiple" to get more than one attachment
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("image/png");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailTo});
emailIntent.putExtra(android.content.Intent.EXTRA_CC, new String[]{emailCC});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailText);
//has to be an ArrayList
ArrayList<Uri> uris = new ArrayList<Uri>();
//convert from paths to Android friendly Parcelable Uri's
if(filePaths != null) {
for (String file : filePaths) {
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
uris.add(u);
}
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
try {
context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_email_using_message)));
}catch (ActivityNotFoundException e) {
new DigitalReplicaDialog(context, context.getResources().getString(R.string.email_not_configured_warning)).show();
}
}

Categories

Resources