`

JavaMail学习--使用JMail发送邮件

    博客分类:
  • Java
 
阅读更多
最近需要用到使用javamail发邮件,网上搜了下相关资料学习了下,怕以后忘记,记录在此。

1.什么是javamail  JavaMail API是读取、撰写、发送电子信息的可选包。
2.javamail开发需要依赖的jar包
   mail.jar(javamail API 目前是1.4.3)-与收发有关的类都在其中
   activation.jar(javabeans activation framework包 目前是1.0.2)--可以提供对Mime类型数据的支持。比如收发附件。

<!-- 官方解释开始 -->
    With the JavaBeans Activation Framework standard extension, developers who use Java technology can take advantage of standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and to instantiate the appropriate bean to perform said operation(s). For example, if a browser obtained a JPEG image, this framework would enable the browser to identify that stream of data as an JPEG image, and from that type, the browser could locate and instantiate an object that could manipulate, or view that image.

<!--官方解释结束 -->

3.HelloJavaMail 使用javamail通过163邮件服务器递送一封纯文本邮件


Java代码  收藏代码

    public static void sendTxtMail() 
        { 
           Properties props = new Properties(); 
           props.put("mail.smtp.host", "smtp.163.com"); //smtp服务器地址 
     
           props.put("mail.smtp.auth", true);  //是否需要认证 
            
           /**实例化一个验证里,继承abstract Authenticator
            * 实现    
            *   protected PasswordAuthentication getPasswordAuthentication(){
            *       return new PasswordAuthentication(userName,password);
            *   }
            */  
           MyAuthenticator myauth = new MyAuthenticator("账号","密码"); 
           //获得一个带有authenticator的session实例 
           Session session = Session.getInstance(props,myauth); 
           session.setDebug(true);//打开debug模式,会打印发送细节到console 
           Message message = new MimeMessage(session); //实例化一个MimeMessage集成自abstract Message 。参数为session 
           try 
           { 
           message.setFrom(new InternetAddress("83378122@163.com")); //设置发出方,使用setXXX设置单用户,使用addXXX添加InternetAddress[] 
     
           message.setText("只是一个简简单单的文本内容哟!"); //设置文本内容 单一文本使用setText,Multipart复杂对象使用setContent 
     
           message.setSubject("只是简简单单的文本标题哟!"); //设置标题  
     
           message.setRecipient(Message.RecipientType.TO, new InternetAddress("dxt02880466@qq.com")); //设置接收方 
     
          Transport.send(message); //使用Transport静态方法发送邮件 
       
           }catch(AddressException e) 
           { 
               //此处处理AddressException异常  [The exception thrown when a wrongly formatted address is encountered.]  
     
           }catch(MessagingException e) 
           { 
               //此处处理MessagingException异常 [The base class for all exceptions thrown by the Messaging classes ] 
           } 
            
        } 
       



写法二:

Java代码  收藏代码

    public static void sendTxtMail() 
        { 
           Properties props = new Properties(); 
         
           Session session = Session.getInstance(props,null); 
           session.setDebug(true);//打开debug模式,会打印发送细节到console 
           Message message = new MimeMessage(session); //实例化一个MimeMessage集成自abstract Message 。参数为session 
           try 
           { 
           message.setFrom(new InternetAddress("83378122@163.com")); //设置发出方,使用setXXX设置单用户,使用addXXX添加InternetAddress[] 
     
           message.setText("只是一个简简单单的文本内容哟!"); //设置文本内容 单一文本使用setText,Multipart复杂对象使用setContent 
     
           message.setSubject("只是简简单单的文本标题哟!"); //设置标题  
     
           message.setRecipient(Message.RecipientType.TO, new InternetAddress("dxt02880466@qq.com")); //设置接收方 
     
                 /**
                 *使用静态方法每次发送需要建立一个到smtp服务器的链接,你可以手动控制连接状态 ,通过session获得tansport,连接到mailserver,而session就可以使用Session.getDefaultInstance(props,null);获得     */ 
               Transport transport = session.getTransport("smtp"); 
          transport.connect(("smtp.163.com","账号", "密码"); 
           transport.sendMessage(message, message.getAllRecipients()); 
           transport.close(); 
           }catch(AddressException e) 
           { 
               //此处处理AddressException异常  [The exception thrown when a wrongly formatted address is encountered.]  
     
           }catch(MessagingException e) 
           { 
               //此处处理MessagingException异常 [The base class for all exceptions thrown by the Messaging classes ] 
           } 
            
        } 
     
       



4.发送HTML内容的邮件
   把HTML内容的邮件通过前面的代码发出去会使代码原样显示在邮件里,故需要对代码进行简单修改。其中HTML中的img需来自网上。

   修改设置content的代码
 
Java代码  收藏代码

    message.setContent("<b><font color=\"red\">带颜色的HTML内容</font></b>","text/html;charset=utf8"); 
    charset用于设置内容的编码格式 



5.HelloJavaMail发送带有附件的邮件

Java代码  收藏代码

    //发送带有附件的邮件,将邮件的每个部分初始化一个bodypart。 
        //邮件是由多个部分组成,每个部分称为一个邮件体部分,是一个 BodyPart 类对象, 
        //对于 MIME 类型 邮件来讲就是 MimeBodyPart 类对象.这些邮件体包含在成为 Multipart 的容器中 
        public static void sendMailWithAttachment(){ 
             
            Properties props = new Properties(); 
            Session session = Session .getDefaultInstance(props); 
            Message message = new MimeMessage(session); 
            try 
            { 
            message.setSubject("这个是带有附件的标题"); 
            message.setFrom(new InternetAddress("83378122@163.com")); 
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("dxt02880466@qq.com")); 
            Multipart multipart = new MimeMultipart(); 
            //实例化一个bodypart用于封装内容 
            BodyPart bodyPart = new MimeBodyPart(); 
            bodyPart.setContent("<font color='red'>这个是带有附件的HTML内容</font>","text/html;charset=utf8"); 
            //添加bodypart到multipart 
            multipart.addBodyPart(bodyPart); 
            //每一个部分实例化一个bodypart,故每个附件也需要实例化一个bodypart 
            bodyPart = new MimeBodyPart(); 
            //实例化DataSource(来自jaf),参数为文件的地址 
            DataSource dataSource = new FileDataSource(file.getAbsolutePath()); 
            //使用datasource实例化datahandler 
            DataHandler dataHandler = new DataHandler(dataSource); 
            bodyPart.setDataHandler(dataHandler); 
            //设置附件标题,使用MimeUtility进行名字转码,否则接收到的是乱码 
            bodyPart.setFileName(javax.mail.internet.MimeUtility.encodeText(file.getName())); 
            multipart.addBodyPart(bodyPart); 
            message.setContent(multipart); 
            Transport transport = session.getTransport("smtp"); 
            transport.connect("smtp.163.com","账号" , "密码"); 
            transport.sendMessage(message, message.getAllRecipients()); 
            transport.close(); 
            }catch(MessagingException  e) 
            {}catch(UnsupportedEncodingException e){} 
             
        } 




结尾:

      初学javamail,怕遗忘就记录在这里。有时间会详细学习下一些细节。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics