Hi dear readers.
In 2022, It's little bit typical to send e-mail to any other mail service providers using java programming due to security reasons all mail id providers has restricted the access from third parties from 30th May 2022.
Here I am explaining the simple java program which can send the mail to any mail server.
You just have to install some jar packages before you start the program. You can use any type of IDE for developing the program, But I prefer Net Beans IDE.
I have tested it on the following configurations : -
JDK 1.8
Net Beans 8.0
Jar files Download ----> activation.jar, java-mail-1.4.4.jar
Java program :
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
// Assign the Recipient's any email addess
String to = "receivername@gmail.com";
// Assign the Sender's hotmail email address only
String from = "sendername@hotmail.com";
Properties properties = System.getProperties();
// Setup outlook mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.host", "m.outlook.com");
properties.put("mail.smtp.auth", "true");
// Get the Session object sender username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sendername@hotmail.com", "sendePassword");
}
});
// Used to debug SMTP issues
session.setDebug(true);
try {
// Create MimeMessage class object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the message header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the message header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is My Subject ");
// Now set the message
message.setText("This is my Message");
System.out.println("Sending the mail ..."+to);
// Send message
Transport.send(message);
System.out.println("E-Mail message sent successfully at "+to+ "mail ID");
} catch (MessagingException e1) {
e1.printStackTrace();
}
}
}
That's it..
For any query please let me know.
Thank you..
Comentários