zoukankan      html  css  js  c++  java
  • java web邮件收发

    1.网上方法要导入两个包    

    mail.jar&activation.jar

    package com.zjh.shopping.util;
    
    import java.util.Date;  
    import java.util.Properties;  
     
    import javax.activation.DataHandler;  
    import javax.activation.FileDataSource;  
    import javax.mail.Authenticator;  
    import javax.mail.Multipart;  
    import javax.mail.PasswordAuthentication;  
    import javax.mail.internet.InternetAddress;  
    import javax.mail.internet.MimeBodyPart;  
    import javax.mail.internet.MimeMultipart;  
    import javax.mail.internet.MimeUtility;  
     
     
    public class JavaMailSendUtil {  
     
         
        public  void sendmail(String subject, String from, String[] to,  
                String text, String[] filenames, String mimeType) {  
            try {  
                Properties props = new Properties();  
     
                String smtp = "smtp.163.com"; // 设置发送邮件所用到的smtp  
                String servername = "*******";  //邮箱账号名
                String serverpaswd = "******";  //邮箱密码
     
                javax.mail.Session mailSession = null; // 邮件会话对象  
                javax.mail.internet.MimeMessage mimeMsg = null; // MIME 邮件对象  
     
                props = java.lang.System.getProperties(); // 获得系统属性对象  
                props.put("mail.smtp.host", smtp); // 设置SMTP主机  
                props.put("mail.smtp.auth", "true"); // 是否到服务器用户名和密码验证  
                // 到服务器验证发送的用户名和密码是否正确  
                SmtpAuthenticator myEmailAuther = new SmtpAuthenticator(servername,  
                        serverpaswd);  
                // 设置邮件会话 注意这里将认证信息放进了Session的创建参数里  
                mailSession = javax.mail.Session.getInstance(props,  
                        (Authenticator) myEmailAuther);  
                // 设置传输协议  
                javax.mail.Transport transport = mailSession.getTransport("smtp");  
               // 设置from、to等信息  
               mimeMsg = new javax.mail.internet.MimeMessage(mailSession);  
               if (null != from && !"".equals(from)) {  
                   InternetAddress sentFrom = new InternetAddress(from);  
                   mimeMsg.setFrom(sentFrom); // 设置发送人地址  
               }  
     
               InternetAddress[] sendTo = new InternetAddress[to.length];  
               for (int i = 0; i < to.length; i++) {  
                   System.out.println("发送到:" + to[i]);  
                   sendTo[i] = new InternetAddress(to[i]);  
               }  
     
               mimeMsg.setRecipients(  
                       javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);  
               mimeMsg.setSubject(subject, "gb2312");  
     
               MimeBodyPart messageBodyPart1 = new MimeBodyPart();  
               // messageBodyPart.setText(UnicodeToChinese(text));  
               messageBodyPart1.setContent(text, mimeType);  
     
               // 附件传输格式  
               Multipart multipart = new MimeMultipart();  
               multipart.addBodyPart(messageBodyPart1);  
     
               for (int i = 0; i < filenames.length; i++) {  
                   MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
     
                   String filename = filenames[i].split(";")[0];  
                   String displayname = filenames[i].split(";")[1];  
                   // 得到数据源  
                   FileDataSource fds = new FileDataSource(filename);  
                   // BodyPart添加附件本身  
                   messageBodyPart2.setDataHandler(new DataHandler(fds));  
                   // BodyPart添加附件文件名  
                   messageBodyPart2.setFileName(MimeUtility  
                           .encodeText(displayname));  
                   multipart.addBodyPart(messageBodyPart2);  
               }  
               mimeMsg.setContent(multipart);  
               // 设置信件头的发送日期  
               mimeMsg.setSentDate(new Date());  
               mimeMsg.saveChanges();  
               // 发送邮件  
               transport.send(mimeMsg);  
               transport.close();  
               System.out.println("发送到成功!!!");  
           } catch (Exception e) {  
               e.printStackTrace();  
           }  
       }  
     
        
       public static void main(String[] args) throws Exception {  
           String title = "测试邮件";// 所发送邮件的标题  
           String from = "************@163.com";// 从那里发送  
           String sendTo[] = { "********@qq.com" };// 发送到那里  
           // 邮件的文本内容,可以包含html标记则显示为html页面  
           String content = "test java send mail !!!!!!<br><a href="http://sjsky.javaeye.com/">My blog</a>";  
         // 所包含的附件,及附件的重新命名  
         String fileNames[] = { "d:\test.jpg;test.jpg" };  
    
         JavaMailSendUtil test = new JavaMailSendUtil();  
         try {  
             // MailSender mailsender = new MailSender();  
             test.sendmail(title, from, sendTo, content, fileNames,  
                     "text/html;charset=gb2312");  
         } catch (Exception ex) {  
             ex.printStackTrace();  
         }  
     }  
    
       
     class SmtpAuthenticator extends Authenticator {  
         String username = null;  
         String password = null;  
    
          
         public SmtpAuthenticator(String username, String password) {  
             super();  
             this.username = username;  
             this.password = password;  
         }  
    
          
         public PasswordAuthentication getPasswordAuthentication() {  
             return new PasswordAuthentication(this.username, this.password);  
           }  
       }  
    }  

    2.自己用的

    package com.gree.mail.mailsend;
    
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
    
    public class Mailsend2 {
        
        
    
    public static Session getSession() {
        Session session = null;
        
    //      session = (Session)new InitialContext().lookup("MailSession");
        
      
          Properties props = new Properties();
          props.put("mail.smtp.host", "10.1.1.168");
          props.put("mail.smtp.auth", "false");
          session = Session.getDefaultInstance(props, null);
        
        return session;
    }
    
    public static void sendMessage(String from, String[] to, String[] cc, String subject, String content,
                                     String mimeType) throws javax.mail.MessagingException {
    
        Message message = new MimeMessage(getSession());
        if (!StringUtils.isEmpty(from)) {
          InternetAddress sentFrom = new InternetAddress(from);
          message.setFrom(sentFrom);
        }
        InternetAddress[] sendTo = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
          sendTo[i] = new InternetAddress(to[i]+"@gree.com.cn");
        }
        if ( (cc.length > 0) && (cc[0] != null)) {
          InternetAddress[] copyTo = new InternetAddress[cc.length];
          for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]+"@gree.com.cn");
          }
          message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    
        //System.out.println("发送人员:"+message.getRecipients(Message.RecipientType.TO));
        //System.out.println("抄送人员:"+message.getRecipients(Message.RecipientType.CC))
    
    
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
     }
     
    public void sendHTMLMessage(String[] to, String[] cc, String title, String content)throws MessagingException {
        
        
        try {
            sendMessage("SCBWEB", to, cc, title+"-模具管理系统信息", content, "text/html;Charset=gb2312");
        } catch (javax.mail.MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
             // System.out.println("2="+content);
    }
    
    public static void main(String[] args) {
        String [] to= new String[] {"180172"};
        String [] cc= new String[] {"180158"};
        String title="ceshi";
        String content="晚上小天请我们吃烤鱼,8号门对面,大概67点左右,等下下班别走开";
        try {
            Mailsend2.sendMessage("180170@gree.com.cn", to, cc, title, content, "text/html;Charset=utf-8");
        } catch (javax.mail.MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
        }
    
    }

    myeclipse中发送邮件出现Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream

    出现这个问题的原因是jar包版本不统一,解决方法如下:
    我在项目导入了jar包

    与myeclipse自带jar冲突了

    删除Java EE 5 Libraries/javaee.jar/mail里的包有东西.

    具体操作:

    进入myeclipse的安装目录:我安装的是myeclipse blue 8.5 具体路径如下

    E:development_toolsmyeclipse_8.5install_dcommonpluginscom.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033datalibrarysetEE_5

    找到javaee.jar,打开后删除mail文件夹即可(需要先关闭运行着的myeclipse,否则无法删除)

  • 相关阅读:
    oracleI基础入门(6)sql语句Substring Crazy
    oracleI基础入门(7)table约束 Crazy
    oracleI基础入门(7)table视图 Crazy
    SQL附加分离数据库(命令)
    双截棍 C语言版 (超搞笑)
    AspNetPage分页(repeater),自己做的例子基本代码
    记录
    RegularExpressionValidator控件中正则表达式用法
    20 个经典的 Ajax + CSS 表格
    GridView各个事件中,怎样获取主键值
  • 原文地址:https://www.cnblogs.com/binggu/p/4390648.html
Copyright © 2011-2022 走看看