sending image in email does not work - android

I am using this code (given below) to send image through email from my android application, the email is received but it does not have the image. Please tell what is issue in my code?
Received Mail:
email body
Code:
package com.example.appdeveloper.appname;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import java.io.File;
import java.util.Properties;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
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;
public class EmailHandler extends AsyncTask<Void, Void, Boolean> {
private static String to = "reciever#example.com";
private static String from = "sender#example.com";
private static String subject = "Subject";
private static String sender = "Android App";
private static String mail;
private static String username = "sender";
private static String password = "password";
EmailHandler(Context context) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/test.png";
mail ="<!DOCTYPE html><html><body><img src="+path+"></body></html>";
}
#Override
protected Boolean doInBackground(Void... nothing) {
try {
Authenticator auth = new EmailAutherticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.user", username);
properties.setProperty("mail.smtp.password", password);
Session session = Session.getDefaultInstance(properties,auth);
MimeMessage message = new MimeMessage(session);
message.setSubject(subject);
message.setContent(mail, "text/html; charset=utf-8");
Address address = new InternetAddress(from,sender);
message.setFrom(address);
InternetAddress ad[] = new InternetAddress[2];
ad[0] = new InternetAddress(to);
ad[1] = new InternetAddress(from);
message.addRecipients( Message.RecipientType.TO, ad );
Transport.send(message);
return true;
}
catch(Exception exp) {
exp.printStackTrace();
return false;
}
}
}
class EmailAutherticator extends Authenticator {
private String username = "sender";
private String password = "password";
public EmailAutherticator() {
super();
}
public EmailAutherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}

So your Email comes across with body like this (kinda):
<!DOCTYPE html><html><body><img src="\myPhone\DCIM\image.png"></body></html>
Your email won't be able to get to that location unless you read email on your phone.
EDIT 1
You can attach extra data to your intent by using Intent.EXTRA_STREAM as outlined in Android documentation here

Related

How to validate otp from api

I'm making OTP based registrations how do I validate my OTP number please help.
here are 2 scripts
1 is a validation activity
2 is an async task running ok http req
3 there is one more activity which takes a user phone number and sends OTP SMS
which is working fine
I just wanna check if OTP on my edit text matches with message user received
package com.example.test2;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
class Verifyotp extends AsyncTask<String, Void, Void> {
public static String string;
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("mobile_no", MainActivity.phoneNo)
.addFormDataPart("otp", OTP_activity.OTP)
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1:8000/api/verifyotp")
.method("POST", body)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
string = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class OTP_activity extends AppCompatActivity {
public static String OTP;
TextView mssg;
EditText ED;
Button ver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_activity);
mssg = (TextView) findViewById(R.id.txtmssg);
ver = (Button) findViewById(R.id.verify);
ED = (EditText)findViewById(R.id.otp);
mssg.setText("We have sent you an SMS on " + MainActivity.phoneNo + " with 4 digit verification code.");
ver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OTP = ED.getText().toString();
Verifyotp chk= new Verifyotp();
chk.execute();
int i = Verifyotp.string.length();
if (i < 20){
Toast.makeText(getApplicationContext(),
"please try again.", Toast.LENGTH_LONG).show();
}
else {
Intent in = new Intent(OTP_activity.this, Home_Acivity.class);
startActivity(in);
}
}
});
}
}
Any help is appreciated
You Could Use Firebase OTP Authentication For This Work.

How to add image attachments from sdcard in email app using javamail API

I'm new to android programming and Android Studio, I'm developing a simple android application that can send a email with attachment. I already can send email but with the attachment part I'm having troubles. When I add the mimebodypart for the attachment I can't receive any emails now. Here's my code
SimpleMail.java
package com.team8.javamail2;
import android.content.Context;
import android.os.Environment;
import java.io.File;
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;
/**
* Created by VEN on 1/27/2019.
*/
public class SimpleMail {
/**CHANGE ACCORDINGLY**/
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER = "unvrsx#gmail.com";
private static final String SMTP_AUTH_PWD = "XXXXXXXXXX";
private static Message message;
private File file ;
private Context context;
public static void sendEmail(String to, String subject, String msg){
// Recipient's email ID needs to be mentioned.
// Sender's email ID needs to be mentioned
String from = "unvrsx#gmail.com"; //from
final String username = SMTP_AUTH_USER;
final String password = SMTP_AUTH_PWD;
// Assuming you are sending email through relay.jangosmtp.net
String host = SMTP_HOST_NAME;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setContent(msg, "text/html");
// Create a multipar message
// Set text message part
// Part two is attachment
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
// Send the complete message partBidt
message.setContent(multipart);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
MainActivity.java
package com.team8.javamail2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private EditText toEmailEditText;
private EditText subjectEditText;
private EditText messageEditText;
private Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toEmailEditText = (EditText) findViewById(R.id.editTextEmail);
subjectEditText = (EditText) findViewById(R.id.editTextSubject);
messageEditText = (EditText) findViewById(R.id.editTextMessage);
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String to = toEmailEditText.getText().toString().trim();
String subject = subjectEditText.getText().toString();
String message = messageEditText.getText().toString();
if(to.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a recipient email", Toast.LENGTH_LONG).show();
}else if(subject.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a Subject", Toast.LENGTH_LONG).show();
}else if(message.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a message", Toast.LENGTH_LONG).show();
}else {
//everything is filled out
//send email
new SimpleMail().sendEmail(to, subject, message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.team8.javamail2">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I don't know if something around here cause the problem
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);

android smtp with attachment of db file

i am trying to create a android smtp app, in which i want to access the internal storage (Where a .db or .db.crypt file is stored) and from there i want to get that file and sent it via email.
below is my code,where everything is working fine. i am able to get that file and send it. but suppose my original file name is "file1.db" but after sending it through smtp it receives as "file1" which is just a file.
any one having idea? plz tell me how can i send that db file???
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
//Class is extending AsyncTask because this class is going to perform a networking operation
public class SendMail extends AsyncTask<Void,Void,Void> {
//Declaring Variables
private Context context;
private Session session;
//Information to send email
private String email;
private String subject;
private String message;
//Progressdialog to show while sending email
private ProgressDialog progressDialog;
//Class Constructor
public SendMail(Context context, String email, String subject, String message){
//Initializing variables
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
progressDialog = ProgressDialog.show(context,"Sending message","Please wait...",false,false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing a success message
Toast.makeText(context,"Message Sent",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Config.EMAIL, Config.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
//Setting sender address
mm.setFrom(new InternetAddress(Config.EMAIL));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(message);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+File.separator+"PasswordSafe.db"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
messageBodyPart.setFileName("file1");
multipart.addBodyPart(messageBodyPart);
mm.setContent(multipart);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}}
This will do the trick for you..
String fileName = name + " yourFile"+".db";

How to connect android app to App engine

I'm Trying to connect my App in Android to a server I've opened on appengine.
My server's name is : dddd-daniel-2345
and the website for the server is : http://dddd-daniel-2345.appspot.com/
This is how to connect from android app to server in app engine:
app.yaml:
application: dddd-daniel-2345
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: .*
script: main.app
libraries:
- name: webapp2
version: "2.5.2"
main.py:
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
from google.appengine.api import users
import webapp2
class UserHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('%s,%s,%s' % (user.email(),user.user_id(),user.nickname()))
else:
greeting = ('not logged in')
self.response.out.write(greeting)
app = webapp2.WSGIApplication([('/', UserHandler),], debug=True)
My Applications code :
add to manifast
Main.Activity:
package com.ap2.demo.comunication;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.ap2.demo.R;
import com.ap2.demo.SplashActivity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
AccountManager accountManager;
private Account[] accounts;
Spinner spinner;
DefaultHttpClient httpClient = new DefaultHttpClient();
Account account;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(getApplicationContext());
// assembling all gmail accounts
accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
// setting spinner to be viewed
spinner = (Spinner) findViewById(R.id.account);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
Button startAuth = (Button) findViewById(R.id.startAuth);
startAuth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner = (Spinner) findViewById(R.id.account);
account = accounts[spinner.getSelectedItemPosition()];
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
Intent intent = new Intent(MainActivity.this, SplashActivity.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
}
else if(resultCode == RESULT_CANCELED){
// user canceled
}
}
}
OnTokenAcquired:
package com.ap2.demo.comunication;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by Daniel on 19-Jun-15.
*/
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
private static final int USER_PERMISSION = 989;
private static final String APP_ID = "dddd-daniel-2345";
// private static final String APP_ID = "dddd-daniel-1234";
private DefaultHttpClient httpclient;
Activity activity;
public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
{
this.httpclient = httpclient;
this.activity = activity;
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, USER_PERMISSION);
} else {
setAuthToken(bundle);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//using the auth token and ask for a auth cookie
protected void setAuthToken(Bundle bundle) {
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookie(httpclient, APP_ID, activity.getBaseContext()).execute(authToken);
}
}
GetCookie:
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class GetCookie extends AsyncTask<String, Void, Boolean> {
String appId;
HttpParams params;
private HttpResponse response;
// private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-2345.appspot.com/";
private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-2345.appspot.com/";
//private static final String LINK_TO_GET_AUTHENTICATED = "http://dddd-daniel-1234.appspot.com/";
Context context;
private DefaultHttpClient httpclient;
public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
{
this.httpclient = httpclient;
params = httpclient.getParams();
this.appId = appId;
this.context = context;
}
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
protected void onPostExecute(Boolean result)
{
new Auth(httpclient, context).execute(LINK_TO_GET_AUTHENTICATED);
}
}
Auth:
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class Auth extends AsyncTask<String, Void, Boolean> {
private DefaultHttpClient httpclient;
private HttpResponse response;
private String content = null;
Context context;
public Auth(DefaultHttpClient httpclient, Context context)
{
this.httpclient = httpclient;
this.context = context;
}
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpGet = new HttpGet(urls[0]);
response = httpclient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
return true;
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return false;
}
//display the response from the request above
protected void onPostExecute(Boolean result) {
Toast.makeText(context, "Response from request: " + content,
Toast.LENGTH_LONG).show();
}
}
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="10dp"
android:text="#string/choose_account"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" />
<Spinner android:id="#+id/account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1" />
<Button
android:id="#+id/startAuth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/account"
android:layout_marginTop="10dp"
android:text="#string/send_button" />
</RelativeLayout>
Whenever I'm running the app it shows me the correct Toast.

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