Using the existing gmail account and send mails - android

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

Related

Getting problems when using MVP model to write a "login" App

I tried to write a "login" App using MVP model. And I use WAMP to build up my server. I'm sure that my php documents have no problem.
Here is the structure of my App:
enter image description here
And here are the files:
User.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
IUserBiz.java
package com.example.android.login.mvp.biz;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserBiz
{
public void login(String username, String password, OnLoginListener loginListener);
}
OnLoginListener.java
package com.example.android.login.mvp.biz;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface OnLoginListener
{
void loginSuccess(User user);
void loginFailed();
}
UserBiz.java
package com.example.android.login.mvp.biz;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public class UserBiz extends AppCompatActivity implements IUserBiz
{
private User user;
private OnLoginListener loginListener;
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
task.execute(test1Url);
}
/**
* Update the UI with the given earthquake information.
*/
private void updateUi(User mUser) {
if (mUser.getStatus()==1)
{
loginListener.loginSuccess(user);
} else
{
loginListener.loginFailed();
}
}
private class LoginAsyncTask extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
// Perform the HTTP request for earthquake data and process the response.
User mUser = Utils.fetchEarthquakeData(urls[0],user);
return mUser;
}
#Override
protected void onPostExecute(User result) {
if(result==null){
return;
}
updateUi(result);
}
}
}
Utils.java
package com.example.android.login.mvp.biz;
import android.text.TextUtils;
import android.util.Log;
import com.example.android.login.mvp.bean.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Utility class with methods to help perform the HTTP request and
* parse the response.
*/
public final class Utils {
/** Tag for the log messages */
public static final String LOG_TAG = Utils.class.getSimpleName();
/**
* Query the USGS dataset and return an {#link User} object to represent a single earthquake.
*/
public static User fetchEarthquakeData(String requestUrl, User user) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url, user);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
// Extract relevant fields from the JSON response and create an {#link User} object
User earthquake = extractFeatureFromJson(jsonResponse);
// Return the {#link User}
return earthquake;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url, User user) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String params="app_user_name="+user.getUsername()+'&'+"app_password="+user.getPassword();
OutputStream out=urlConnection.getOutputStream();
out.write(params.getBytes());//post提交参数
out.flush();
out.close();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return an {#link User} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private static User extractFeatureFromJson(String earthquakeJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
// If there are results in the features array
if (baseJsonResponse.length() > 0) {
int status = baseJsonResponse.getInt("status");
// Create a new {#link User} object
User user=new User();
user.setStatus(status);
return user;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
UserLoginPresenter.java
package com.example.android.login.mvp.presenter;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.biz.IUserBiz;
import com.example.android.login.mvp.biz.OnLoginListener;
import com.example.android.login.mvp.biz.UserBiz;
import com.example.android.login.mvp.view.IUserLoginView;
/**
* Created by zhy on 15/6/19.
*/
public class UserLoginPresenter {
private IUserBiz userBiz;
private IUserLoginView userLoginView;
public UserLoginPresenter(IUserLoginView userLoginView) {
this.userLoginView = userLoginView;
this.userBiz = new UserBiz();
}
public void login() {
userLoginView.showLoading();
userBiz.login(userLoginView.getUserName(), userLoginView.getPassword(), new OnLoginListener() {
#Override
public void loginSuccess(final User user) {
userLoginView.toMainActivity(user);
userLoginView.hideLoading();
}
#Override
public void loginFailed() {
userLoginView.showFailedError();
userLoginView.hideLoading();
}
});
}
public void clear() {
userLoginView.clearUserName();
userLoginView.clearPassword();
}
}
IUserLoginView.java
package com.example.android.login.mvp.view;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserLoginView
{
String getUserName();
String getPassword();
void clearUserName();
void clearPassword();
void showLoading();
void hideLoading();
void toMainActivity(User user);
void showFailedError();
}
UserLoginActivity.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
But I got something wrong like this:
enter image description here
I have no idea about it. How to solve it?
the issue is here
this.userBiz = new UserBiz();
UserBiz is an activity so activity gets their context when they are being started with Intent (by OS) but creating an object of an activity will not provide any contenxt hence the null exception at
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
// no context here due to new UserBiz
// getString required context
task.execute(test1Url);
}
Solution : you can use enums or static final constants to avoid context and also would be wise to substitute UserBiz as separate class instead of an activity

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

Download files synchronously (Android)

I have an array of Urls which I would synchronously.
In fact I'm in an asynctask with a for loop.
I tried using downloadmanager and broadcast receiver without success (the manager use another thread so I can't unregister each time, a leak append).
This is my Asynctask :
package com.ylly.hypred.splashScreen.asynctask;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.WindowManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ylly.hypred.R;
import com.ylly.hypred.api.CallAPI;
import com.ylly.hypred.api.model.MediaAPIModel;
import com.ylly.hypred.api.model.MediaArrayAPIModel;
import com.ylly.hypred.utils.FileManager;
import java.io.File;
import java.util.ArrayList;
/**
* Created by YLLY on 17-11-2015.
*/
public class LoadMedias extends AsyncTask<String, Void, String> {
private MediaArrayAPIModel mediaAPIModels;
private Context context;
private ProgressDialog progressDialog;
private boolean isCallFromUpdate;
private final String TAG = "LoadMedias";
private OnLoadingIsFinished mCallback;
/**
*
*/
public interface OnLoadingIsFinished {
void callProcess();
}
/**
*
* #param context
* #param urls
* #param isCallFromUpdate
*/
public LoadMedias(Context context, MediaArrayAPIModel urls, boolean isCallFromUpdate) {
this.context = context;
this.mediaAPIModels = urls;
progressDialog = new ProgressDialog(context);
this.isCallFromUpdate = isCallFromUpdate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!isCallFromUpdate)
progressDialog.setTitle(context.getString(R.string.fm_etape_trois_sur_trois));
progressDialog.setMessage(context.getString(R.string.fm_enregistrement));
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progressDialog.setMax(mediaAPIModels.getMediaImagePIModels().size() + mediaAPIModels.getMediaFileAPIModels().size());
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
mCallback.callProcess();
}
#Override
protected String doInBackground(String... arg0) {
try {
loadMediaImages(mediaAPIModels.getMediaImagePIModels(), progressDialog);
loadMediaFiles(context, mediaAPIModels.getMediaFileAPIModels(), progressDialog);
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return "";
}
/**
*
* #param onLoadingIsFinished
*/
public void setOnLoadingIsFinished(OnLoadingIsFinished onLoadingIsFinished) {
this.mCallback = onLoadingIsFinished;
}
/**
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaImages(ArrayList<MediaAPIModel> mediaAPIModels, ProgressDialog progressDialog) {
String type;
for (int i = 0; i < mediaAPIModels.size(); i++) {
type = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("."));
if (type.equals(".png") || type.equals(".jpg") || type.equals(".jpeg")) {
ImageLoader.getInstance().loadImageSync(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl());
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
/**
* #param context
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaFiles(Context context, ArrayList<MediaAPIModel> mediaAPIModels, final ProgressDialog progressDialog) {
{
String name;
String mime;
for (int i = 0; i < mediaAPIModels.size(); i++) {
if (!FileManager.getInstance().getFileFromLocal(context, mediaAPIModels.get(i).getUrl(), false)) {
name = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("/") + 1); //on sépare le nom du fichier du reste de l'url
mime = name.substring(name.lastIndexOf(".")); //on recupere l'extension du fichier
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl()));
request.setDescription(context.getResources().getString(R.string.downloading) + " name");
request.setTitle(context.getResources().getString(R.string.app_name));
request.setMimeType(mime);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("test" + File.separatorChar + "doc", name);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
Log.d("DOWNLOAD", "unregister");
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
} else {
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
}
}
The cache loading works.
Thanks in advance ;)

Tweet Multiple Pictures Android

Twitter recently released an update allowing users to attach up to four images to a tweet. I was wondering how to implement this in an Android application.
I've found a post that was made BEFORE Twitter released the update called "Posting multiple photos in a single tweet" (I'm not showing the link because I'm only allowed to show two links with less than 10 reputation).
Now, here is the Twitter API documentation describing how to attach multiple images to a tweet, the only problem is that I have no idea how to implement this in Android:
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
So I was thinking of two possible solutions - either modify one of these methods from the Twitter4j library( https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media) to allow for multiple image attachments OR directly implement the Twitter API documentation.
Any ideas how to do this?
Input is greatly appreciated!
I have shared the multiple images on Twitter in android using twitter4j library,it is working fine to share multiple and single image on twitter
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class SharingActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "sample_twitter_pref";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final int WEBVIEW_REQUEST_CODE = 223;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
ImageView loginLayout,shareLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTwitterConfigs();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
findViewById(R.id.twitBtnId).setOnClickListener(this);
findViewById(R.id.btn_share).setOnClickListener(this);
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn) {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.commit();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
private void initTwitterConfigs() {
consumerKey = getString(R.string.twitter_consumer_key);
consumerSecret = getString(R.string.twitter_consumer_secret);
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = getString(R.string.twitter_oauth_verifier);
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(callbackUrl);
final Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (responseCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.twitBtnId:
loginToTwitter();
break;
case R.id.btn_share:
new ShareImage().execute();
break;
}
}
public class ShareImage extends AsyncTask<Void,Void,String>{
#Override
protected void onPreExecute() {
//show progress here
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
return uploadMultipleImages();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//hide progress here
Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
}
}
public String uploadMultipleImages() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
long[] mediaIds = new long[4];
for (int i=0; i<4; i++) {
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
if (isCompres) {
UploadedMedia media = twitter.uploadMedia(tempFile);
mediaIds[i] = media.getMediaId();
tempFile.deleteOnExit();
}
}
StatusUpdate update = new StatusUpdate("test_name0");
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
public String uploadSingleImage() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate update = new StatusUpdate("test_name0");
update.setMedia(tempFile);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
}
public class WebViewActivity extends Activity {
private WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
}
for running above code please download the below library and put it in your app libs folder and add it as dependency in gradle file
(1)twitter4j-core-4.0.4.jar
(2)twitter4j-media-support-4.0.4.jar
(3)twitter4j-stream-4.0.4.jar
(4)signpost-commonshttp4-1.2.1.1.jar
(5)signpost-core-1.2.1.1.jar
(6)signpost-jetty6-1.2.1.1.jar
It is working fine, hope it will help for you also

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