栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java中javamail发送带附件的邮件实现方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java中javamail发送带附件的邮件实现方法

本文实例讲述了java中javamail发送带附件的邮件实现方法。分享给大家供大家参考。具体分析如下:

JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输,JavaMail是可选包,因此如果需要使用的话你需要首先从java官网上下载。目前最新版本是JavaMail1.5.0,下面我们来看看javamail发送带附件的邮件实例

mail.java 代码:
复制代码 代码如下:package mail; 
 
import java.util.* ; 
import java.io.* ; 
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 file = new Vector(); //用于保存发送附件的文件名的集合
    
     
    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; 
    } 
    
     
    public void setUserName(String username){ 
        this.username=username; 
    } 
    
     
    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(){ 
        
    } 
    
     
    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; 
    } 
    
     
    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 send(){ 
        HashMap map=new HashMap(); 
        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 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(); 
             }  
        } 
        //System.out.println("n提示信息:"+message); 
        map.put("message", message); 
        return map; 
    } 
}
SmtpAuth.java 代码:
复制代码 代码如下:package mail; 
 
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);
    }  
}

存在的问题就是发送到163的邮件全部都带有一个附件的符号,不管有没有发送附件,感兴趣的朋友可以对此加以改进和完善。

希望本文所述对大家的Java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/151841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号