是否可以使用GMail帐户从我的Java应用程序发送邮箱?我已经用Java应用程序配置了我公司的邮件服务器来发送邮箱,但当我发布应用程序时,这并不能阻止它.任何使用Hotmail、雅虎或GMail的答案都是可以接受的.
是否可以使用GMail帐户从我的Java应用程序发送邮箱?我已经用Java应用程序配置了我公司的邮件服务器来发送邮箱,但当我发布应用程序时,这并不能阻止它.任何使用Hotmail、雅虎或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中的哪些方法调用抛出异常,这样您就可以更好地了解如何正确处理它们.)
感谢@jodonnel人和其他所有回答的人.我要赏金给他,因为他的回答让我走了大约95%的路,得到了一个完整的答案.