Writing a Mail Sender In Java
To write a mail sender in Java, you can use the JavaMail API, which provides a set of classes for sending and receiving emails using the Simple Mail Transfer Protocol (SMTP) and other email protocols. Here's an example of how to send an email using the JavaMail API:
java
Copy code
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailSender {
public static void main(String[] args) {
// SMTP server configuration
String smtpHost = "smtp.gmail.com";
String smtpPort = "587";
String smtpUser = "your_username@gmail.com";
String smtpPassword = "your_password";
// Sender and recipient email addresses
String from = "your_username@gmail.com";
String to = "recipient_email@example.com";
// Email message configuration
String subject = "Test Email";
String body = "This is a test email from Java.";
// Set SMTP server properties
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a Session object with authentication
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUser, smtpPassword);
}
});
try {
// Create a new email message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Send the email message
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException ex) {
System.err.println("Error sending email: " + ex.getMessage());
}
}
}
In this example, we use the JavaMail API to configure the SMTP server properties, authenticate the user credentials, and create a MimeMessage object with the sender and recipient email addresses, subject, and body text. Finally, we send the email message using the Transport.send() method.
Note that you will need to include the JavaMail API JAR file in your classpath to use this code. You can download the JavaMail API from the Oracle website or from Maven Central.