挑战: 启用跨各种 Java 应用程序的电子邮件传送电子邮件提供商。
JavaMail API:
作为重要资源,请下载 JavaMail API 以将必要的 jar 文件包含在应用程序的类路径中。如需全面的电子邮件处理,请考虑实施此强大的 API。
GMail 示例:
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { // Replace with your GMail credentials private static String USER_NAME = "*****"; private static String 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) { // Set up SMTP configuration with GMail's parameters 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 sender, recipient, subject, and body of the email message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { toAddress[i] = new InternetAddress(to[i]); } for (int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); 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(); } } }
其他提示:
以上是如何使用 Gmail、Yahoo 或 Hotmail 从我的 Java 应用程序轻松发送电子邮件?的详细内容。更多信息请关注PHP中文网其他相关文章!