How to send mail in android
Sending mail in Android can be done using the Android's built-in Intent system. Here's a step-by-step guide on how to send a mail in Android:
Method 1: Using the Android's built-in Intent
- Create a new Intent object:
Intent intent = new Intent(Intent.ACTION_SEND);
- Set the type of the intent to "message/rfc822" which is the MIME type for email:
intent.setType("message/rfc822");
- Set the recipient's email address:
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
- Set the subject of the email:
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of the email");
- Set the body of the email:
intent.putExtra(Intent.EXTRA_TEXT, "Body of the email");
- Start the intent:
startActivity(Intent.createChooser(intent, "Send Email"));
This will open the default email client on the device and allow the user to send the email.
Method 2: Using a third-party library
You can also use a third-party library such as JavaMail or Apache Commons Email to send mail in Android. Here's an example of how to use JavaMail:
- Add the JavaMail library to your project:
dependencies { implementation 'com.sun.mail:android-mail:1.6.2' }
- Create a new instance of the
GmailTransport
class:GmailTransport transport = new GmailTransport();
- Set the recipient's email address:
transport.setRecipient(new InternetAddress("[email protected]"));
- Set the subject of the email:
transport.setSubject("Subject of the email");
- Set the body of the email:
transport.setTextBody("Body of the email");
- Send the email:
transport.send();
Note: You need to have the necessary permissions to send email in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SEND_SMS" />
Also, you need to have a valid email account set up on the device for the email to be sent successfully.
Example Code
Here's an example code that demonstrates how to send a mail in Android using the Android's built-in Intent:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of the email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of the email");
startActivity(Intent.createChooser(intent, "Send Email"));
And here's an example code that demonstrates how to send a mail in Android using JavaMail:
GmailTransport transport = new GmailTransport();
transport.setRecipient(new InternetAddress("[email protected]"));
transport.setSubject("Subject of the email");
transport.setTextBody("Body of the email");
transport.send();