如果您使用 Sun 提供的 JavaMail api,您可以从 Sun Downloads 获取最新的 api。.
JavaMail 使用属性将所有配置加载到程序中。.
您必须指定
# SMTP 服务器的主机名或 IP 地址
mail.smtp.host=smtp.duke.java.sun.com
# 您可以获得大量调试信息,如果
# 已打开。注释此行以打开
# 关闭。.
mail.debug=true
# 收件人电子邮件地址
ttapr2004.to=duke@duke.java.sun.com
# 发件人电子邮件地址
ttapr2004.from=duke@j2ee_fanclub.java.su…
您无需验证即可轻松连接到 SMTP 服务器。但您可能会遇到无法从 Java 程序发送电子邮件的情况:
1.您的 IP 地址可能被防火墙拦截,无法登录。 访问 SMTP 服务器
2.您的 SMTP 服务器屏蔽了发件人地址、收件人地址,也许还有您的 IP 地址。.
3.您的 SMTP 服务器需要验证
如果您的服务器需要身份验证,可从互联网上获取该信息
-------------...
公共类 SendMailUsingAuthentication {
private static final String SMTP_HOST_NAME = "myserver.smtphost.com";;
private static final String SMTP_AUTH_USER = "myusername";;
private static final String SMTP_AUTH_PWD = "mypwd";;
private static final String emailMsgTxt =
"在线订单确认信息。还包括跟踪号码";;
private static final String emailSubjectTxt = "订单确认主题";;
private static final String emailFromAddress = "sudhir@javacommerce.com";;
// 添加需要向其发送电子邮件的电子邮件地址列表
private static final String[] emailList = {
"mark@yahoo.com"、"robin@javacommerce.com"};;
public static void main(String args[]) throws Exception {
SendMailUsingAuthentication smtpMailSender = new
SendMailUsingAuthentication();;
smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt、,
emailFromAddress);;
System.out.println("Sucessfully Sent mail to All Users");;
}
public void postMail(String recipients[], String subject、,
String message, String from) 引发 MessagingException {
boolean debug = false;;
//设置主机 smtp 地址
Properties props = new Properties();;
props.put("mail.smtp.host", SMTP_HOST_NAME);;
props.put("mail.smtp.auth", "true");;
Authenticator auth = new SMTPAuthenticator();;
会话 session = Session.getDefaultInstance(props, auth);;
session.setDebug(debug);;
// 创建一条信息
Message msg = new MimeMessage(session);;
// 设置发件人和收件人地址
InternetAddress addressFrom = new InternetAddress(from);;
msg.setFrom(addressFrom);;
InternetAddress[] addressTo = new InternetAddress[recipients.length];;
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);;
}
msg.setRecipients(Message.RecipientType.... addressTo);;
// 设置主题和内容类型
msg.setSubject(subject);;
msg.setContent(message, "text/plain");;
Transport.send(msg);;
}
/**
* SimpleAuthenticator 用于进行简单的身份验证
* 当 SMTP 服务器需要时。.
*/
私有类 SMTPAuthenticator
扩展 javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
字符串 username = SMTP_AUTH_USER;;
字符串 password = SMTP_AUTH_PWD;;
return new PasswordAuthentication(username, password);;
}
}
}
-------------...
免责声明--本文所表达的观点由第三方提供,可能与本网站的观点不一致
