Home >Java >javaTutorial >How Can I Send Emails from Java Using Gmail, Yahoo, or Hotmail?
Sending Emails from Java using Gmail, Yahoo, or Hotmail
Introduction:
Sending emails from Java applications can be essential for various purposes, including notifications, order confirmations, and customer outreach. This article explores the process of sending emails through Java using popular email providers such as Gmail, Yahoo, and Hotmail.
Requirements:
To begin, you will need:
Using Gmail:
The following Java code snippet demonstrates how to send an email using Gmail:
import javax.mail.*; import javax.mail.internet.*; public class EmailSender { public static void main(String[] args) { String from = "myUserName@gmail.com"; String password = "myPassword"; String recipient = "recipient@example.com"; String subject = "Java Email"; String body = "This is a test email sent from Java."; try { // Set up mail properties Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // Create the mail session Session session = Session.getDefaultInstance(props, null); // Create the email message MimeMessage message = new MimeMessage(session); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddress = new InternetAddress(recipient); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, toAddress); message.setSubject(subject); message.setText(body); // Send the email Transport transport = session.getTransport("smtp"); transport.connect("smtp.gmail.com", from, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Email sent successfully!"); } catch (MessagingException e) { e.printStackTrace(); } } }
Using Yahoo or Hotmail:
The general process for sending emails using Yahoo or Hotmail is similar to that of Gmail. However, there may be slight variations in the SMTP server address and configuration.
Conclusion:
This article provides a comprehensive guide on sending emails from Java applications using popular email providers like Gmail, Yahoo, and Hotmail. By following the steps outlined above, you can seamlessly integrate email functionality into your applications and enhance user communication.
The above is the detailed content of How Can I Send Emails from Java Using Gmail, Yahoo, or Hotmail?. For more information, please follow other related articles on the PHP Chinese website!