如何通过Java应用程序使用GMail,Yahoo或Hotmail发送电子邮件?

问题:

可以使用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(); } } } [/code] 自然地,您需要在catch块中做更多的比打印堆栈跟踪,就像我在上面的示例代码中所做的那样。 (删除catch块以查看JavaMail API中的哪个方法调用抛出异常,以便您可以更好地了解如何正确处理它们。)
感谢@jodonnel和所有回答的人。我给他一个赏金,因为他的回答让我95%的方式得到一个完整的答案。

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How can I send an email by Java application using GMail, Yahoo, or Hotmail?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 4 = 3