MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Java Mail API in Android

In this article will learn how we can make use of Java Mail API to send Mail in Android automatically and also some details about fetching email-ID’s from the Android device that is configured for mail service.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

To create an Android application that are capable of sending an automatic mail without prompting user for to address, from address, subject and body of mail. In a simple word, we need to create an Android app that sends mail on click of a button with from address of the user to a particular mail-ID.

Need of Sending Automatic Mail?

In order to answer this question, let’s take a scenario of an Application that sends some system information to the server like Details of the Employee’s Mobile phone to Company’s server for some security purpose.

Task to complete

  • Create an Android Application with UI that contains one button.
  • When user clicks on that button an automatic mail send to particular mail-ID (company’s mail-ID) with some details of user mobile like list of installed application in phone.

Step by Step

To accomplish above task will follow following steps:

Open Eclipse and create an Android application using New->Android Application Project. In my case project name: SendAutoMail with Activity name: MainActivity.java with layout file name: activity_main.xml.(See the image below)

Shows the steps to create Android app. Enter the Name of project , Package Name and select Minimum SDK and Target SDK

Figure 1: Shows the steps to create Android app. Enter the Name of project , Package Name and select Minimum SDK and Target SDK.

In activity_main.xml create one button with text property set to “Send Log”.

<Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Send Log" />

Now we learn something about Java Mail API.

As we know that Android make use of java classes and interfaces so it is quite possible to add previously written java class or interfaces in android for some task.

“The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.”

You will find this line in oracle website for JavaMail. So Java Mail is required when we need to create our own mail application for sending so shots of information.

In our application we are going to use following things from JavaMail API:

  • Multipart class: - it allow to device message into multipart so that long message can be sent easily.
  • Session: - in order to send mail we need to create session between hosts.
  • InternetAddress : it contains address , simply maid ID (example: abc@xyz.com).
  • Similarly, you will find many classes inside this mail.jar for more information you can visit oracle.com.

  • In order to get this mail.jar file follow this link http://javamail-android.googlecode.com/files/mail.jar , apart from this link you can also find mail.jar in the code provided to you with this article.
  • Now you need to add this mail.jar into you build path so that we can use required classes. In order to add this jar to your build path follow these simple steps:
    • Copy mail.jar into “libs” folder present inside your mail project. If not there please create one.
    • Now right click on mail.jar inside libs folder and select option “Build Path” and then select “Add to Build Path”.
    • Now for clarification you can check your “Referenced Libraries”. You will find mail.jar inside it and that indicate you have successfully added it to build path. Now you are ready to use classes from mail.jar.

Next step is to create a class for creating mail service that is used to send mail. For this article I have created a class named: “MailService.java” that contain method sendEmail() for sending mail with following code:

Listing 1: MailService.java

public void sendEmail() throws AddressException, MessagingException {
		String host = "smtp.gmail.com";
		String address = "address@gmail.com";
		
		String from = "fromaddress@gmail.com";
		String pass = "password";
		String to="toaddress@gmail.com";
		
		Multipart multiPart;
		String finalString="";
		

		Properties props = System.getProperties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", address);
		props.put("mail.smtp.password", pass);
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.auth", "true");
		Log.i("Check", "done pops");
		Session session = Session.getDefaultInstance(props, null);
		DataHandler handler=new DataHandler(new ByteArrayDataSource(finalString.getBytes(),"text/plain" ));
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setDataHandler(handler);
		Log.i("Check", "done sessions");
		
		multiPart=new MimeMultipart();

		InternetAddress toAddress;
		toAddress = new InternetAddress(to);
		message.addRecipient(Message.RecipientType.TO, toAddress);
		Log.i("Check", "added recipient");
		message.setSubject("Send Auto-Mail");
		message.setContent(multiPart);
		message.setText("Demo For Sending Mail in Android Automatically");
		
		
		
		Log.i("check", "transport");
		Transport transport = session.getTransport("smtp");
		Log.i("check", "connecting");
		transport.connect(host,address , pass);
		Log.i("check", "wana send");
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		
		Log.i("check", "sent");

	}

Note: In the above code address, to, from and password variable should be replaced by actual value for the security purpose only unreal values are used.

For this article I have used gmail as a host and smtp as protocol. If you want to send mail using other host server you need to use host address of that.

Next we learn how to fetch various information from the Mobile phone. For this tutorials I will show how to get the list of installed application in the mobile phone and how to fetch the email –id’s from the mobile that is configured by the user.

So our first task it to find the list of installed applications. For that we need to write following code:

Listing 2: Listing Installed Applications

String installed_apps=new String();
		installed_apps="List of Installed Apps:\n\n";
		final PackageManager pm=getPackageManager();
		
		List<ApplicationInfo> packages=pm.getInstalledApplications(PackageManager.GET_META_DATA);
		
		int i=0;
		for(ApplicationInfo packageinfo:packages){
			
			installed_apps=installed_apps+"\n\t\t\t"+(i+1)+":"+packageinfo.processName;
			i++;
		}

In the above code first we have created the instance of PackageManager that consist of information about the packages (application is also refer to as package that is every application have unique package name. it is like primary key).

Then, using List class with parameter ApplicationInfo we called the method getInstalledApplications(PackageManager.GET_META_DATA ) to get the list of installed application information into packages.

After that by simply iterating through List and calling processName will get list of installed application and here we are appending each package name into a string variable installed_apps.

Now the next task is to get list of running applications. For that again we required simple code:

Listing 3: Listing running applications

String running_apps=new String();
		running_apps="List of Running Apps:\n\n";			
		ActivityManager manager=(ActivityManager) MainActivity.this.getSystemService(ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> processes=manager.getRunningAppProcesses();
		int k=0;
		int ss=processes.size();
		for(RunningAppProcessInfo process:processes)
		{
			running_apps=running_apps+"\n\t\t\t"+(k+1)+":"+process.processName;
			k++;
		}

In the above code we used ActivityManager class that is used to manage all the activities or process currently running.

And again by using List with parameter RunningAppProcessInfo we got list of running process information and after that just by calling processName property we got running application package name.

Next we find the email-Id configured in the device. Using following code we can accomplished this task:

Listing 4: Finding the email-Id configured in the device

String emailID=new String();
				Pattern emailPattern=Patterns.EMAIL_ADDRESS;
				Account []accounts=AccountManager.get(mContext).getAccounts();
				for(Account account:accounts)
				{
					if(emailPattern.matcher(account.name).matches())
					{
						emailID=emailID+account.name+"\n\t\t\t\t";
					}
				}

Note: In order to fetch email-ID we require certain permission that you need to define in the AndroidManifest.xml file.

We require the code below for fetching email-ID.

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>

Similarly , for sending email we require the two codes below:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

And

<uses-permission android:name="android.permission.INTERNET"/>

Using this article now we are able to send mail automatically and able to fetch certain records about Mobile Device.

OUTPUTS

When you run the project you will see the image above that display a button. After you click the button it will start sending mail

Figure 2: When you run the project you will see the image above that display a button. After you click the button it will start sending mail.

Above image showing the process of sending mail using Toast

Figure 3: Above image showing the process of sending mail using Toast.

After successful sending of mail again a toast message is shown for informing user that particular mail has been sent.

Figure 4: After successful sending of mail again a toast message is shown for informing user that particular mail has been sent.

Conclusion

We learnt today on the process of working with Java Mail API, will come with some more great stuff next time.



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login