问题:
Java 应用程序可以使用电子邮件帐户像 GMail、Yahoo 或 Hotmail 一样发送电子邮件?如何实现这一点?
答案:
第 1 步:导入 JavaMail API
在继续之前,请确保您已下载所需的 JavaMail API jar 并将其添加到您的
第 2 步:GMail 配置
以下 Java 代码片段演示使用 GMail 帐户发送电子邮件:
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(); } } }
注意: 将 USER_NAME、PASSWORD、RECIPIENT、subject 和 body 变量替换为适当的
其他注意事项:
以上是Java 应用程序如何通过 Gmail、Yahoo 或 Hotmail 发送电子邮件?的详细内容。更多信息请关注PHP中文网其他相关文章!