how to send email from an android application - android

I have tried this till now
register.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Username = username.getText().toString();
Email = email.getText().toString();
System.out.println("clicked register Button");
System.out.println(" User name is :" + Username );
System.out.println(" Email Id is :" + Email);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , Email);
i.putExtra(Intent.EXTRA_EMAIL , Email);
i.putExtra(Intent.EXTRA_SUBJECT, "You are registered for Aero india");
i.putExtra(Intent.EXTRA_TEXT , "Get the print out of this email while coming to the venue");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}
});

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to send email
*
* #author FaYna Soft Labs
*/
public class Main extends Activity {
private Button clickBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Send email");
clickBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[]{"my#email.com", "",};
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is email's message");
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
}
});
}
}

Related

Launch other activity after createChooser

How can you redirect to another activity once the application that was launched by createChooser such as show below is complete?
My attempt below ends up with the second intent being triggered before the createChooser launches. I noticed that when I press the back button on the newly launched activity is when the createChooser appears on the activity I wanted to launch it from.
I also tried to wrap the createChooser in startActivityForResult and then launch the second intent using onActivityResult but the result was the same
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
startActivity(trackIntent);
Here's the entire code:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InformContacts extends Activity {
private static String ITEM_NAME = "Item name";
private static String ITEM_PRICE = "Item price";
private static String ITEM_PIC_URI = "Item pic uri";
public static final int REQUEST_SEND_EMAIL = 0;
ArrayList<Contact> listContacts;
ListView lvContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inform_contacts);
listContacts = new ContactFetcher(this).fetchAll();
lvContacts = (ListView) findViewById(R.id.lvContacts);
final ContactsAdapter adapterContacts = new ContactsAdapter(this, listContacts);
lvContacts.setAdapter(adapterContacts);
final Button informButton = (Button) findViewById(R.id.button6);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String uriSharedPref = preferences.getString(ITEM_PIC_URI, "item pic uri");
informButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList emailsList = adapterContacts.emailsSelected;
String item = preferences.getString(ITEM_NAME, "item name");
Float price = preferences.getFloat(ITEM_PRICE,0);
//May use the uriSharedPref string to embed actual url in email and show recipients like I did with publishing house
String sellingMessage = "Hello,\n\nI'm selling my "+ item +" for KES "+price+".\n\nGet back to me if you're interested in buying.\n\n" + uriSharedPref;
String subject = "Selling my "+item;
sendEmail(emailsList, sellingMessage, subject);
//Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
//startActivity(trackIntent);
}
});
}
protected void sendEmail(ArrayList<String> arrayOfEmails, String message, String subject) {
Log.i("Send email", "");
Intent emailIntent = new Intent(Intent.ACTION_SEND);
//First Step: convert ArrayList to an Object array
Object[] objEmails = arrayOfEmails.toArray();
//Second Step: convert Object array to String array
String[] strEmails = Arrays.copyOf(objEmails, objEmails.length, String[].class);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, strEmails);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
if(isIntentSafe){
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), REQUEST_SEND_EMAIL);
//finish();
Log.i("Done sending email...", "");
}
else{
Toast.makeText(InformContacts.this, "No email app found. Email won't be sent.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}
}
}
Try this
Change to:
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
Instead of:
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}

send a image from gallery in email service in android

I want to send images via email in my android app. For which I'm using Android Native Camera app and Intents to use the respective service. I've used the following code:
Email is getting send but if I'm trying to add image the app gets crash.
public class Complaints extends AppCompatActivity {
Button sendEmail;
EditText to, subject, msg;
Bitmap image;
Button camera;
File pic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaints);
to = (EditText) findViewById(R.id.et1);
subject = (EditText) findViewById(R.id.et2);
msg = (EditText) findViewById(R.id.et3);
sendEmail = (Button) findViewById(R.id.s_Email);
camera = (Button) findViewById(R.id.btn_img);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"Select Picture"));
}
});
sendEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Emailid = to.getText().toString();
String sub = subject.getText().toString();
String message = msg.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{Emailid});
email.putExtra(Intent.EXTRA_SUBJECT, sub);
email.putExtra(Intent.EXTRA_TEXT, message);
email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//this will make such that when user returns to your app, your app is displayed, instead of the email app.
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
email.setType("message/rfc822");
email.setType("image/jpeg");
try {
startActivity(Intent.createChooser(email, "Message was Sent"));
}
catch (ActivityNotFoundException e) {
Toast t = Toast.makeText(Complaints.this, "There is No Emial Client installed ", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 10);
t.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
image = (Bitmap) data.getExtras().get("Data");
ImageView i = (ImageView) findViewById(R.id.img);
i.setImageBitmap(image);
try
{
File root= Environment.getExternalStorageDirectory();
if(root.canWrite())
{
pic=new File(root,"pic.jpeg");
FileOutputStream out=new FileOutputStream(pic);
image.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
}
} catch (IOException e)
{
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
}
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class Complaints extends Activity {
Button send;
Bitmap thumbnail;
File pic;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaints);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
Button camera = (Button) findViewById(R.id.button1);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"dummy#email.com"});
i.putExtra(Intent.EXTRA_SUBJECT,"dummy subject");
//Log.d("URI#!##!#!###!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
i.setType("image/png");
startActivity(Intent.createChooser(i,"Share this"));
}
});
}
Getting The Image Path and converting path into Uri :
File photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Fault", imagename+".png")
Uri imageuri = Uri.fromFile(photo);
Sending through Email Intent :
Intent send_report = new Intent(Intent.ACTION_SEND);
send_report.putExtra(Intent.EXTRA_EMAIL, new String[]{ email_emailid});
send_report.putExtra(Intent.EXTRA_SUBJECT, email_subject);
send_report.putExtra(Intent.EXTRA_STREAM, imageuri);
send_report.putExtra(Intent.EXTRA_TEXT, email_body);
send_report.setType("text/plain");
send_report.setType("image/png");
startActivityForResult(Intent.createChooser(send_report, "Choose an Email client"), 77);

Automatically close application when i call intent.createChooser to send mail?

In my android application having one button to send mail, When I click that send button using startActivity(Intent.createChooser(emailIntent, "Send Mail...")); this line Gmail will open and then I click send mail. Mail will sent successfully at the same time my application get closed why ? I need to stay in that same page ?
try
{
String extpath=Environment.getExternalStorageDirectory() +"/NewFolder/DBName";
File pathp=new File(extpath);
Log.d("New Path", pathp.toString());
long fileSize = pathp.length();
if(fileSize > 0)
{
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String address = "mailid#yourmail.com";
String subject = "Database";
String emailtext = "Please check the attached database and save it";
emailIntent.setType("application/octet-stream");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { address });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + pathp));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);
startActivity(Intent.createChooser(emailIntent, "Send Mail..."));
}
else
{
Log.d("Error", "Attachment didn't attach ");
}
}
catch (Throwable t)
{
Log.d("Error on sending mail", t.toString());
}
When i run this code mail sent and then application will get close. I don't want to close application. Help me thanks in advance.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button button;
Session session;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SendMailBySite bySite=new SendMailBySite();
bySite.execute();
}
class SendMailBySite extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setMessage("Sending mail.....");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
final String user="XXXXXXXX#gmail.com";//change accordingly
final String password="XXXXXXX";//change accordingly
String to="toXXXXXXXX#gmail.com";//change accordingly
//Get the session object
Properties props = new Properties();
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");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Mobiappsdevelper");
message.setText("This is simple program of sending email using JavaMail API");
//send the message
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "message sent successfully...", 3000).show();
}
}
}
You Can Use This Code:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

send video from sdcard to perticular emaill address

video attachment can not send to particular email address.
I have created an application that sends an email with a recording video, when the intent is fired and email is chosen as the app to send the attachment, you can see that there is an attachment but the attachment is not delivered
package com.example.emailnew;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("video/mp4");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"123#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "video");
i.putExtra(Intent.EXTRA_TEXT , "evidence");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://sdcard/Pictures/Mycameravideos/VIDS.mp4"));//pngFile
startActivity(Intent.createChooser(i, "Send mail..."));
}
});
}
}
Try this code.
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("video/mp4");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {
"mail--id" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
Uri uri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "Pictures/Mycameravideos/VIDS.mp4"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));\
and ya don't forget to add this below permission to your menifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

how to set text on "to" textarea in email activity

i have made an activity
at subscribe button, i have to send email to some default email for which my code is:
package sditm.app;
import android.R.string;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class subscribeActivity extends Activity {
/** Called when the activity is first created. */
EditText name,age,address;
databaseforsubscribe addressBook;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subscribe);
Button store = (Button)findViewById(R.id.button1);
name=(EditText)findViewById(R.id.editText1);
age=(EditText)findViewById(R.id.editText2);
address=(EditText)findViewById(R.id.editText3);
addressBook = new databaseforsubscribe(this,"addressDB",null,2);
store.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String s=new String();
String m=new String();
String n=new String();
s=name.getText().toString();
m=age.getText().toString();
n=address.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL, "aman4251#gmail.com");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"aman4251#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT ,"NAME: "+s+" ; MOBILE: "+m+" ; EMAIL: "+n);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(subscribeActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
which open an intent like this
now either i have to set the email id to "To" textbox (and make it uneditable"), or to automatically click on that "send" button so that user dont see this intent and email is send in back ground..
Try this code:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.",Toast.LENGTH_SHORT).show();
}
Hi try this piece of code
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// Add attributes to the intent
sendIntent.putExtra(Intent.EXTRA_EMAIL, "");
sendIntent.putExtra(Intent.EXTRA_CC, "");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
sendIntent.putExtra(Intent.EXTRA_TEXT, "");
sendIntent.setType("text/plain");
PackageManager pm = getPackageManager();
List<ResolveInfo> activityList = pm
.queryIntentActivities(sendIntent, 0);
Iterator<ResolveInfo> it = activityList.iterator();
boolean isEmailSetUp = false;
while (it.hasNext()) {
ResolveInfo info = it.next();
if ("com.android.email.activity.MessageCompose"
.equalsIgnoreCase(info.activityInfo.name)) {
isEmailSetUp = true;
sendIntent.setClassName(info.activityInfo.packageName,
info.activityInfo.name);
}
}
if (isEmailSetUp) {
startActivity(sendIntent);
} else {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("No Mail Accounts");
dlgAlert.setTitle("Please set up a Mail account in order to send email");
dlgAlert.setPositiveButton(getResources().getString(R.string.ok),
null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
i dono know whether it is possible to make the email id edit text uneditable
But you can send mail in background by click on button
for that refer this link

Categories

Resources