java发送hotmail邮件_如何使用Gmail、Yahoo或Hotmail通过Java应用程序发送电子邮件?...
首先下載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?
toAddress[i]?=?new?InternetAddress(to[i]);
}
for(?int?i?=?0;?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塊,以查看來自JavaMailAPI的哪個方法調用會拋出異常,這樣您就可以更好地了解如何正確處理它們。)
總結
以上是生活随笔為你收集整理的java发送hotmail邮件_如何使用Gmail、Yahoo或Hotmail通过Java应用程序发送电子邮件?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 驾照理论考试android应用
- 下一篇: js 进度条demo