Question:
Can Java applications utilize email accounts like GMail, Yahoo, or Hotmail to send emails? How can this be achieved?
Answer:
Step 1: Import JavaMail API
Before proceeding, ensure that you have downloaded and added the required JavaMail API jars to your classpath.
Step 2: GMail Configuration
The following Java code snippet demonstrates sending an email using a GMail account:
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "[email protected]"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // List of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { // Set email properties message.setFrom(new InternetAddress(from)); // Create InternetAddress array for recipients InternetAddress[] toAddress = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { toAddress[i] = new InternetAddress(to[i]); } // Set recipients for (InternetAddress addr : toAddress) { message.addRecipient(Message.RecipientType.TO, addr); } // Set subject and body message.setSubject(subject); message.setText(body); // Establish connection and send email Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } }
Note: Replace the USER_NAME, PASSWORD, RECIPIENT, subject, and body variables with the appropriate values.
Additional Considerations:
The above is the detailed content of How Can Java Applications Send Emails via Gmail, Yahoo, or Hotmail?. For more information, please follow other related articles on the PHP Chinese website!