How to send mail in java code
In Java, you can send an email using the JavaMail API. Here's a step-by-step guide to help you get started:
Prerequisites:
- Download and install the JavaMail API from the official website: https://javaee.github.io/javamail/
- Add the JavaMail API jar file to your project's classpath.
Code Example:
Here's a simple example of how to send an email using JavaMail API:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Set up the email properties
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");
props.put("mail.smtp.starttls.enable", "true");
// Create a session
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email-username", "your-email-password");
}
});
// Create a message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email-username"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient-email-username"));
message.setSubject("Test Email");
message.setText("This is a test email sent using JavaMail API.");
// Send the message
Transport.send(message);
}
}
Explanation:
- We create a
Properties
object to set up the email properties, such as the SMTP host, port, authentication, and TLS enablement. - We create a
Session
object using theSession.getInstance()
method, passing theProperties
object and anAuthenticator
object. - We create a
MimeMessage
object using theSession
object. - We set the sender, recipient, subject, and body of the email using the
setFrom()
,setRecipient()
,setSubject()
, andsetText()
methods. - We send the email using the
Transport.send()
method.
Note:
- Replace
your-smtp-host
,your-smtp-port
,your-email-username
, andyour-email-password
with your actual email server settings and credentials. - Make sure to enable TLS (Transport Layer Security) in your email server settings to ensure secure email transmission.
- This is a basic example, and you may need to add additional features, such as attachments, HTML content, or error handling, depending on your specific requirements.