1、
下载javamail以及jaf(如使用jdk6则不用),地址分别为61C0BCFFD3F10BFD928C3D8C7718423 和706F9CE9A4EFE38DA6E ,若有变动,可到sum的top downloads里面找,
2、
解压获得mail.jar和activation.jar,将其放在classpath或工程目录下
3、
用法示例
import javax.mail.*;
import javax.mail.internet.*;
try {
String mailSever = "smtp.126.com";
String from = "sender@126.com";
String to = "rcver@gmail.com";
String userName= "sender";
String passwd = "password";
String subject = "The exam";
String content = "Can you notice me of the exam?";
java.util.Properties props = System.getProperties();
props.put("mail.host", mailSever);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth","true");
Authenticator auth = new MyAuth(userName, passwd);
javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, auth);
mailSession.setDebug(true);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress( from ));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress( to ));
msg.setSubject(subject);
msg.setSentDate(new java.util.Date());
msg.setText(content);
Transport.send(msg);
System.out.println(" Sucess !");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
|
其中MyAuth类的定义为:class MyAuth extends Authenticator
{
String UserName = null;
String Password = null;
public MyAuth(String UserName,String Password) {
this.UserName = UserName;
this.Password = Password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(UserName, Password);
}
}
|
特别注意props.put("mail.smtp.auth","true");这句很重要,否则容易招致Relay access denied的异常
另外,目前发现无法用gmail邮箱发邮件,但可以用它收邮件。不知道google搞什么鬼,这么吝啬。
阅读(651) | 评论(0) | 转发(0) |