是否可以使用 GMail 帐户从我的 Java 应用程序发送电子邮件?我已经使用 Java 应用程序配置了我的公司邮件服务器来发送电子邮件,但是当我分发应用程序时这不会减少它。使用 Hotmail、Yahoo 或 GMail 中的任何一个的答案都是可以接受的。
首先下载JavaMail API并确保相关的 jar 文件在您的类路径中。
这是一个使用 GMail 的完整工作示例。
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; 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 { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses 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(); } } }
自然,您会想要在catch块中做更多的事情,而不是像我在上面的示例代码中那样打印堆栈跟踪。(删除这些catch块以查看来自 JavaMail API 的哪些方法调用会引发异常,以便您更好地了解如何正确处理它们。)
catch