How to solve NetworkOnMainThreadException error in android? [closed] - android

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I used javamail to send email in android. But it throws the Exception NetworkOnMainThreadException. How to solve this exception?
MainActivity
package com.aaa;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private Mail m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m = new Mail("mail#gmail.com", "pwd");
}
public void sendEmail(View view){
String[] toArr = {"samp#gmail.com"};
m.setTo(toArr);
m.setFrom("mail613#gmail.com");
m.setSubject("subject");
m.setBody("your message goes here");
try {
//m.addAttachment("/sdcard/myPicture.jpg");
if(m.send()) {
// success
Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
// failure
Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
// some other problem
//Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show(e);
Toast.makeText(MainActivity.this, ""+e+"", Toast.LENGTH_LONG).show();
Log.e("SendMail",e.getMessage(),e);
}
}
}
Mail.java
package com.aaa;
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 _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);
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) {
this._to = toArr;
}
public void setFrom(String string) {
this._from = string;
}
public void setSubject(String string) {
this._subject = string;
}
// more of the getters and setters …..
} `

You need to use an AsyncTask to do all your network operations.
Your network operation can take a lot of time and the UI would get unresponsive if it is done on the main UI thread. And if your UI freezes for a long time, the app might get killed by the OS.
Thus Android 4+ makes it mandatory to use a background thread to perform network operations.
Put the code to do the network activity inside doInBacground() and all the AsyncTask using execute().
Here is how your AsyncTask would look like :
private class SendMail extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
        sendEmail();
 }
 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }
  protected void onPreExecute() {
     //called before doInBackground() is started
 }
 protected void onPostExecute() {
     //called after doInBackground() has finished 
 }
  }
And you can call it anywhere using new SendMail().execute("");

You are trying to access the network on your UI thread. This is bad because it will freeze the UI until the network response has returned. You should do this network access on a separate thread.
There are many options, but the simplest option would be:
Convert msg in MimeMessage msg = new MimeMessage(session); to be final.
Wrap Transport.send(msg); as
new Thread(new Runnable() {
#Override
public void run() {
Transport.send(msg);
}
}).start();
You can equally use an AsyncTask which will allow you to update the UI after in onPostExecute (or you can get this behaviour by creating a Handler on the UI thread and post()ing to it.

Don't do network tasks on the main thread.
Use an AsyncTask

This problem you can find if you will search it as Raghav told in comment.But just some basic explanation,If you do any network(internet) related task in your app,then prefer to do in any other thread rather than in Main UIThread.So you can go for Asynctask or Service.If the task is leangthy then Service is better else you can go for Asyntask.HTH :)

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

Android: Send e-mail with attachment automatically in the background [duplicate]

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

Categories

Resources