`
八贤王
  • 浏览: 39970 次
社区版块
存档分类
最新评论

JAVA 发邮件

    博客分类:
  • JAVA
阅读更多
package com.zbxsoft.commmon;

import java.util.* ;                                                                                                                                    
import javax.mail.* ;                                                                                                                                   
import javax.mail.internet.* ;                                                                                                                          
import javax.activation.* ;                                                                                                                             
public class Mail {                                                                                                                                     
//定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等                                                                                              
private String displayName;                                                                                                                              
private String to;                                                                                                                                       
private String from;                                                                                                                                     
private String smtpServer;                                                                                                                               
private String username;                                                                                                                                 
private String password;                                                                                                                                 
private String subject;                                                                                                                                  
private String content;                                                                                                                                  
private boolean ifAuth; //服务器是否要身份认证                                                                                                           
private String filename="";                                                                                                                              
private Vector<String> file = new Vector<String>(); //用于保存发送附件的文件名的集合                                                                                     
                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置SMTP服务器地址                                                                                                                                    
*/                                                                                                                                                      
public void setSmtpServer(String smtpServer){                                                                                                            
   this.smtpServer=smtpServer;                                                                                                                          
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置发件人的地址                                                                                                                                      
*/                                                                                                                                                      
public void setFrom(String from){                                                                                                                        
   this.from=from;                                                                                                                                      
}                                                                                                                                                        
/**                                                                                                                                                      
* 设置显示的名称                                                                                                                                        
*/                                                                                                                                                      
public void setDisplayName(String displayName){                                                                                                          
   this.displayName=displayName;                                                                                                                        
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置服务器是否需要身份认证                                                                                                                            
*/                                                                                                                                                      
public void setIfAuth(boolean ifAuth){                                                                                                                   
   this.ifAuth=ifAuth;                                                                                                                                  
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置E-mail用户名                                                                                                                                      
*/                                                                                                                                                      
public void setUserName(String username){                                                                                                                
   this.username=username;                                                                                                                              
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置E-mail密码                                                                                                                                        
*/                                                                                                                                                      
public void setPassword(String password){                                                                                                                
   this.password=password;                                                                                                                              
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置接收者                                                                                                                                            
*/                                                                                                                                                      
public void setTo(String to){                                                                                                                            
   this.to=to;                                                                                                                                          
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置主题                                                                                                                                              
*/                                                                                                                                                      
public void setSubject(String subject){                                                                                                                  
   this.subject=subject;                                                                                                                                
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 设置主体内容                                                                                                                                          
*/                                                                                                                                                      
public void setContent(String content){                                                                                                                  
   this.content=content;                                                                                                                                
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 该方法用于收集附件名                                                                                                                                  
*/                                                                                                                                                      
public void addAttachfile(String fname){                                                                                                                 
   file.addElement(fname);                                                                                                                              
}                                                                                                                                                        
                                                                                                                                                        
public Mail(){                                                                                                                                           
                                                                                                                                                        
}                                                                                                                                                        
                                                                                                                                                        
/**                                                                                                                                                      
* 初始化SMTP服务器地址、发送者E-mail地址、用户名、密码、接收者、主题、内容                                                                              
*/                                                                                                                                                      
public Mail(String smtpServer,String from,String displayName,String username,String password,String to,String subject,String content){                   
    this.smtpServer=smtpServer;                                                                                                                         
    this.from=from;                                                                                                                                     
    this.displayName=displayName;                                                                                                                       
    this.ifAuth=true;                                                                                                                                   
    this.username=username;                                                                                                                             
    this.password=password;                                                                                                                             
    this.to=to;                                                                                                                                         
    this.subject=subject;                                                                                                                               
    this.content=content;                                                                                                                               
}                                                                                                                                                       
                                                                                                                                                        
/**                                                                                                                                                     
* 初始化SMTP服务器地址、发送者E-mail地址、接收者、主题、内容                                                                                           
*/                                                                                                                                                     
public Mail(String smtpServer,String from,String displayName,String to,String subject,String content){                                                  
    this.smtpServer=smtpServer;                                                                                                                         
    this.from=from;                                                                                                                                     
    this.displayName=displayName;                                                                                                                       
    this.ifAuth=false;                                                                                                                                  
    this.to=to;                                                                                                                                         
    this.subject=subject;                                                                                                                               
    this.content=content;                                                                                                                               
}                                                                                                                                                       
                                                                                                                                                        
/**                                                                                                                                                     
* 发送邮件                                                                                                                                             
*/                                                                                                                                                     
public HashMap<String,String> send () throws Exception{                                                                                                                                  
    HashMap<String,String> map=new HashMap<String,String>();                                                                                                                          
    map.put("state", "success");                                                                                                                        
    String message="邮件发送成功!";                                                                                                                    
    Session session=null;                                                                                                                               
    Properties props = System.getProperties();                                                                                                          
    props.put("mail.smtp.host", smtpServer);                                                                                                            
    if(ifAuth){ //服务器需要身份认证                                                                                                                    
        props.put("mail.smtp.auth","true");                                                                                                             
        SmtpAuth smtpAuth=new SmtpAuth(username,password);                                                                                              
        session=Session.getDefaultInstance(props, smtpAuth);                                                                                            
    }else{                                                                                                                                              
        props.put("mail.smtp.auth","false");                                                                                                            
        session=Session.getDefaultInstance(props, null);                                                                                                
    }                                                                                                                                                   
    //session.setDebug(true);                                                                                                                             
    Transport trans = null;                                                                                                                             
    //try {                                                                                                                                               
        Message msg = new MimeMessage(session);                                                                                                         
        try{                                                                                                                                            
            Address from_address = new InternetAddress(from, displayName);                                                                              
            msg.setFrom(from_address);                                                                                                                  
        }catch(java.io.UnsupportedEncodingException e){                                                                                                 
            e.printStackTrace();                                                                                                                        
        }                                                                                                                                               
        InternetAddress[] address={new InternetAddress(to)};                                                                                            
        msg.setRecipients(Message.RecipientType.TO,address);                                                                                            
        msg.setSubject(subject);                                                                                                                        
        Multipart mp = new MimeMultipart();                                                                                                             
        MimeBodyPart mbp = new MimeBodyPart();                                                                                                          
        mbp.setContent(content.toString(), "text/html;charset=gb2312");                                                                                 
        mp.addBodyPart(mbp);                                                                                                                            
        if(!file.isEmpty()){//有附件                                                                                                                    
            Enumeration<String> efile=file.elements();                                                                                                          
            while(efile.hasMoreElements()){                                                                                                             
                mbp=new MimeBodyPart();                                                                                                                 
                filename=efile.nextElement().toString(); //选择出每一个附件名                                                                           
                FileDataSource fds=new FileDataSource(filename); //得到数据源                                                                           
                mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart                                                                  
                mbp.setFileName(fds.getName());  //得到文件名同样至入BodyPart                                                                           
                mp.addBodyPart(mbp);                                                                                                                    
            }                                                                                                                                           
            file.removeAllElements();                                                                                                                   
        }                                                                                                                                               
        msg.setContent(mp); //Multipart加入到信件                                                                                                       
        msg.setSentDate(new Date());     //设置信件头的发送日期                                                                                         
        //发送信件                                                                                                                                      
        msg.saveChanges();                                                                                                                              
        trans = session.getTransport("smtp");                                                                                                           
        trans.connect(smtpServer, username, password);                                                                                                  
        trans.sendMessage(msg, msg.getAllRecipients());                                                                                                 
        trans.close();                                                                                                                                  
                                                                                                                                                        
    /*}catch(AuthenticationFailedException e){                                                                                                            
         map.put("state", "failed");                                                                                                                    
         message="邮件发送失败!错误原因:\n"+"身份验证错误!";                                                                                          
         e.printStackTrace();                                                                                                                           
    }catch (MessagingException e) {                                                                                                                     
         message="邮件发送失败!错误原因:\n"+e.getMessage();                                                                                           
         map.put("state", "failed");                                                                                                                    
         e.printStackTrace();                                                                                                                           
         Exception ex = null;                                                                                                                           
         if ((ex = e.getNextException()) != null) {                                                                                                     
             System.out.println(ex.toString());                                                                                                         
             ex.printStackTrace();                                                                                                                      
         }                                                                                                                                              
    }       */
                                                                    
    map.put("message", message);                                                                                                                        
    return map;                                                                                                                                         
}                                                                                                                                                       

public static void main(String[] args) {
Mail m = new Mail();
//发送邮件服务器(smtp)
m.setSmtpServer("smtp.zbxsoft.com");
m.setIfAuth(true);

m.setSubject("测试");
m.setContent("javamail邮件测试<br/><font color=\"red\">你好么-_-</font>");
m.setDisplayName("船长");


m.setUserName("dfzhao");
m.setPassword("123");
m.setFrom("dfzhao@zbxsoft.com");
m.setTo("cbqiu@zbxsoft.com");

try {
m.send();
} catch (Exception e) {

System.out.println("异常"+e.getMessage());
}
}
  }                                                                                                                                            
/********************************************************************/
package com.zbxsoft.commmon;

public class SmtpAuth extends javax.mail.Authenticator {                         
   private String username,password;                                              
                                                                                  
   public SmtpAuth(String username,String password){                              
       this.username = username;                                                  
       this.password = password;                                                  
   }                                                                              
    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {     
        return new javax.mail.PasswordAuthentication(username,password);          
    }                                                                             
}                                                                               
/***************************

如果你用myEclipse进行开发的话,运行时可能会出现以下的错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
原因是jar包版本不统一,解决方法如下:
删除myEclipse安装目录下
\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\javaee.jar


*****************************************/
          
分享到:
评论

相关推荐

    java发邮件 java发email

    4. **创建Message对象**:`Message`对象代表邮件本身,使用`MimeMessage`类创建它,并设置发件人、收件人、主题和正文。例如: ```java MimeMessage message = new MimeMessage(session); message.setFrom(new ...

    java发邮件相关jar包

    在“java发邮件相关jar包”中,可能包含以下关键库: 1. **JavaMail API**: 这是Java用来处理邮件的核心库,包括`javax.mail`和`javax.mail.internet`这两个主要的包。它们提供了邮件协议(如SMTP、POP3、IMAP)的...

    java发邮件代码

    3. **创建Message对象**:使用Session对象创建一个Message实例,设置邮件的基本信息,如发件人、收件人、主题和正文。 ```java Message message = new MimeMessage(session); message.setFrom(new InternetAddress...

    java 发邮件例子

    以下是一个基于`commons-email-1.1`库的Java发邮件实例: 首先,确保你的项目已经正确地引入了`commons-email`库。这通常通过Maven或Gradle的依赖管理来完成。如果你使用的是Maven,可以在`pom.xml`文件中添加以下...

    java发邮件完整以及各个邮箱的设置

    JavaMail是Java编程语言中用于发送和接收电子邮件的标准API,它是通过JavaMail API来实现的。这个API提供了与SMTP(简单邮件传输协议)服务器交互的能力,使得开发者可以在应用程序中轻松地发送邮件。在这个主题中,...

    java发邮件用到的jar包

    在本例中,"java发邮件用到的jar包"指的是用于处理电子邮件的Java类库。下面将详细解释如何使用这些jar包以及相关的知识点。 首先,JavaMail API是Java中处理邮件的核心库,它提供了发送和接收电子邮件的接口。为了...

    用java发邮件(保证秒懂)

    通过实例,用java发邮件,保证秒懂, Xmail xmail = new Xmail(); xmail.setUsername("/////@163.com"); //设置发件人邮箱名字 xmail.setPassword("*******"); //邮箱密码 xmail.setHost("smtp.163.com"); //...

    java 发邮件项目

    综上所述,"java 发邮件项目"涵盖的内容广泛,包括了邮件系统的配置、邮件对象的构建、网络通信以及异常处理等多个方面。通过这个项目,开发者可以学习到如何在Java环境中实现可靠且灵活的邮件发送功能。

    java 发邮件带excel附件,以流的形式发送附件,不生成excel文件

    接下来,我们需要创建一个`MimeMessage`对象,并设置必要的邮件属性,如发件人、收件人、主题和正文。然后,我们将通过`MimeBodyPart`和`MimeMultipart`类来处理附件。 关键在于如何以流的形式创建Excel附件。我们...

    java发邮件所需架包

    在Java编程中,发送电子邮件是一项常见的任务,而这个“java发邮件所需架包”则包含了完成这项任务所需的两个关键库:activation和mail。这两个库是JavaMail API的一部分,提供了发送和接收电子邮件的功能。 首先,...

    java发邮件 源码注释

    java发邮件

    java发邮件程序

    这个“java发邮件程序”的主题涵盖了JavaMail API的使用,它是Java平台上的标准邮件处理库。下面我们将深入探讨如何使用JavaMail API编写一个简单的邮件发送程序。 首先,你需要在项目中引入JavaMail相关的依赖。...

    java发邮件,亲测有效

    标签中的“java发邮件”指的是使用Java编程语言发送邮件。在Spring Boot项目中,我们可以引入`spring-boot-starter-mail`依赖来支持邮件服务。在Maven的pom.xml文件中,这可以通过添加以下代码实现: ```xml ...

    Java发邮件jar包

    这个Java发邮件jar包提供的功能可能更加强大,包括支持HTML邮件、添加附件、处理抄送和密送等功能。使用时,请参照官方文档或者提供的示例代码,结合自己的需求进行适当的调整。记住,始终遵循最佳实践,确保发送...

    java发邮件要用到的4个jar包

    当需要自动发邮件到制定的mail地址时,我们需要这4个jar包 注:如果jar包引用不当,则依然不能发邮件 使用步骤:1、先将jar包放入到ant%home%下的lib文件夹下,比如我的ant%home%是:D:\apache-ant-1.7.0\lib 2、...

    java 发邮件 多收件人 多抄送人 多附件

    java 发邮件工具类 多收件人 多抄送人 多附件 内有三个重载方法 使用方便

    java发邮件相关包

    "java发邮件包"可能包含以下核心库: 1. **javax.mail.jar**:这是Java Mail API的核心库,提供了邮件操作所需的所有接口和类。 2. **activation.jar**:JavaBeans Activation Framework (JAF)库,用于处理不同类型...

    Java 发邮件教程含示例代码

    Java 发邮件功能是Java应用程序与外部世界交互的重要方式之一,特别是在自动化通知、系统日志记录或者用户服务中。本文将详细介绍如何使用Java发送邮件,并提供示例代码。 首先,发送邮件需要依赖JavaMail API和...

    java发邮件注册

    "java发邮件注册"这个主题涉及到的是利用JavaMail API来实现通过电子邮件进行用户账户的激活过程。以下将详细介绍这一过程中的关键知识点。 首先,我们需要理解JavaMail API。这是一个用于处理邮件的开源库,它允许...

    java发邮件依赖jar包.zip

    在这个名为“java发邮件依赖jar包.zip”的压缩文件中,包含了两个关键的JAR文件:mail.jar和activation.jar,它们是JavaMail API的核心组成部分。 JavaMail API 是Java平台上的一个开源库,用于处理电子邮件相关的...

Global site tag (gtag.js) - Google Analytics