How to send email using organization mail in java

To send an email using an organization's mail server in Java, you can use the JavaMail API. Here's a step-by-step guide:

Prerequisites:

  1. Download and install the JavaMail API from the official website: https://javaee.github.io/javamail/
  2. Add the JavaMail API jar file to your project's classpath.

Code Example:

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-organization-mail-server-host");
        props.put("mail.smtp.port", "your-organization-mail-server-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-organization-email-username", "your-organization-email-password");
            }
        });

        // Create a message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("your-organization-email-username"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient-email-address"));
        message.setSubject("Email Subject");
        message.setText("Email Body");

        // Send the message
        Transport.send(message);
    }
}

Explanation:

  1. Set up the email properties: You need to specify the host, port, and authentication details of your organization's mail server.
  2. Create a session: Use the Session class to create a session object, passing in the email properties and an authenticator object.
  3. Create a message: Use the MimeMessage class to create a message object, setting the from address, recipient address, subject, and body.
  4. Send the message: Use the Transport class to send the message.

Tips: