Chinaunix首页 | 论坛 | 博客
  • 博客访问: 190067
  • 博文数量: 31
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 981
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-20 09:18
文章分类
文章存档

2011年(3)

2010年(8)

2009年(1)

2008年(19)

我的朋友

分类: Java

2008-03-06 11:19:35

1、  下载javamail以及jaf(如使用jdk6则不用),地址分别为61C0BCFFD3F10BFD928C3D8C7718423 706F9CE9A4EFE38DA6E ,若有变动,可到sumtop downloads里面找,

2、  解压获得mail.jaractivation.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) |
给主人留下些什么吧!~~