How to send mail using java
Sending mail using Java can be done using the JavaMail API. Here's a step-by-step guide:
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 sending an email using Java:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
// Set up the mail server 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 mail server properties, such as the host, port, authentication, and TLS encryption. - 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's email address using the
setFrom()
method. - We set the recipient's email address using the
setRecipient()
method. - We set the subject and body of the email using the
setSubject()
andsetText()
methods. - We send the message using the
Transport.send()
method.
Note:
- Replace
your-smtp-host
,your-smtp-port
,your-email-username
, andyour-email-password
with your actual mail server settings and credentials. - Make sure to enable TLS encryption and authentication in your mail server settings.
- This is a basic example, and you may need to add more features, such as attachments, HTML content, or CC/BCC recipients, depending on your specific requirements.