Cannor send mail using javax.mail in android
A common issue!
To send email using javax.mail
in Android, you need to follow these steps:
-
Add the
javax.mail
library to your project: You can do this by adding the following dependency to yourbuild.gradle
file:dependencies { implementation 'com.sun.mail:android-mail:1.6.2' }
-
Get the
Session
object: Create aSession
object using the following code:Properties props = new Properties(); props.put("mail.smtp.host", "your-smtp-host"); props.put("mail.smtp.port", "your-smtp-port"); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your-email", "your-password"); } });
Replace
"your-smtp-host"
,"your-smtp-port"
,"your-email"
, and"your-password"
with your actual SMTP server details. -
Create a
Message
object: Create aMessage
object using the following code:Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient-email")); message.setSubject("Your Subject"); message.setText("Your message");
Replace
"your-email"
and"recipient-email"
with the actual email addresses. -
Send the email: Use the
Transport
class to send the email:Transport.send(message);
Here's the complete code:
import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties;
public class EmailSender { public static void sendEmail(String smtpHost, int smtpPort, String email, String password, String recipientEmail, String subject, String message) { Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); } });
Message messageObj = new MimeMessage(session);
messageObj.setFrom(new InternetAddress(email));
messageObj.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
messageObj.setSubject(subject);
messageObj.setText(message);
Transport.send(messageObj);
}
}
Call the `sendEmail` method with the required parameters to send the email.
Note: Make sure to handle exceptions properly and add necessary permissions to your AndroidManifest.xml file:
```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />