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