Email Without Intent - android

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.

Related

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.

Send password directly to email obtained from edittext on button click

I am facing a problem whole day but not able to find the solution. Plz guide
Tried below mentioned code but did not get any email ,I am sending new password to user email whenuser enter his email on edittext and on submit button password is send to email id entered by user.I am doing this work on Forget Password Activity.I have read many Links of sending email without user interventions but did not get solution.Please help me to know what is the problem in below code .I have added three jars Mail.jar,additional.jar,activation.jar and also added files to gradle and still facing problem.
package com.example.emailsendnoui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivitySecond extends Activity {
Button send_btn ;
EditText mail_id_text ;
String mail ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_2);
send_btn = (Button) findViewById(R.id.button1_send);
mail_id_text = (EditText) findViewById(R.id.editText1_mailId);
Log.v("hari","edittext text"+mail_id_text.getText());
send_btn.setOnClickListener(new OnClickListener() {
#SuppressLint("ShowToast")
#Override
public void onClick(View v) {
if(mail_id_text != null) {
StringBuilder str_mail = new StringBuilder() ;
str_mail.append(mail_id_text.getText());
mail = str_mail.toString();
Log.v("hari", "mail:"+mail);
/*StringBuilder str = new StringBuilder() ;
str.append("ErrorName:").append("MalformedURLException :--`");`
str.append("e.getClass").append("--`").append("e.getMessage");*/`
String s = "12345" ;
Log.v("hari", "Response Before:"+s);
emailsend(s);
} else {
Toast.makeText(getApplicationContext(), "Pls enter mail id", Toast.LENGTH_SHORT).show();`
}
}
});
}
private void emailsend(String serverresponse) {
try {
GMailSender sender = new GMailSender("monikacse623#gmail.com", "abc32"); // type ur mail id and password here and next line also
sender.sendMail("Subject : This is Hari Testing ","Body: ServerRespHere: GET new password from DB here:"+serverresponse,"monikacse623#gmail.com",mail);
Toast.makeText(getApplicationContext(), "Email Send Successfully...", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.v("hari","send email"+ e.getMessage(), e);
}
}
}
package com.example.emailsendnoui ;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.Security;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.activation.DataHandler;
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 javax.sql.DataSource;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String `sender, String recipients) throws Exception {`
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new `ByteArrayDataSource(body.getBytes(), "text/plain"));`
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, `InternetAddress.parse(recipients));`
else
message.setRecipient(Message.RecipientType.TO, new `InternetAddress(recipients));`
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource, `javax.activation.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");
}
#Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
#Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
#Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public Connection getConnection() throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public Connection getConnection(String theUsername, String `thePassword)`
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
}
You can try this:
for send email by chooser:
protected void sendEmail() {
Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
for direct send mail, you can follow link:
sending email without user interaction android
https://www.mindstick.com/Articles/1673/sending-mail-without-user-interaction-in-android
I hope this will help you. thanks

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

How to send mail programmatically in android using OAuth2.0 token

I am developing an app in which I want to send mail programmatically using Gmail credentials, I know how to access device mail id and token using AccountManager. Please suggest me how to send mail using credentials with some code or tutorial. I am new to Android. Please help me thanks in advance..
After very hard work now i am able to login to Google using Oauth 2. now i am sharing here coz many questions are unanswered here. Below steps are require to login to Google.
1- Select a account from your device using
public static AccountManager accountManager;
accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
2- Get a Token from selected account using
private void onAccountSelected(final Account account) {
accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
useToken(account, token);
} catch (OperationCanceledException e) {
onAccessDenied();
} catch (Exception e) {
handleException(e);
}
}
}, null);
}
3- now Authenticate the Token using user account and Token. you will be able to login to google.
Note: After sometime token get unauthorized to login so you need to invalidate your token.
4- for re login you have to invalidate your token using
accountManager.invalidateAuthToken("com.google", token);
5- after invalidate you have to get a new token using
String newToken = AccountManager.get(this).getAuthToken(new Account(account, "com.google"),
AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
6- in your AndroidManifest.xml add below uses permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
Thats all you require, now enjoy
fist you download activation.jar,mail.jar,additionnal.jar and add to built to your project
And code r following
---------Create GMailSender.class
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
e.printStackTrace();
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
2-Create JSSEProvider.class
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
3-use This code in to your Activity button click etc..
try {
GMailSender sender = new GMailSender("sender gmail ID", "password");
sender.sendMail("This is Subject",
"This is Body",
"receiverID",
"receiverID");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
Source: https://stackoverflow.com/a/2033124/865900 (credit where credit is due)

Embedd inline images using JAVA Mail in 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();
}
}

Categories

Resources