`

用Java Mail发送带图片附件

阅读更多
1,读入图片的方式:
发现网上讲的很多读取图片的方式都不对,按下面提供的这个方法来读取,保证成功。

java 代码

private   byte [] getImageBytes(String file) {  
    byte [] myData =  null ;  
    InputStream input = getClass().getClassLoader().getResourceAsStream(file);  
    try  {  
        ByteArrayOutputStream byteArray = new  ByteArrayOutputStream();  
        int  ch =  0 ;  
        while  ((ch = input.read()) != - 1 ) {  
        byteArray.write(ch);  
    }  
    // System.out.println(byteArray.size());   
    myData = byteArray.toByteArray();  
    // System.out.println(myData.length);   
    }  
    catch  (Exception e) {  
        e.printStackTrace();}  
        return  myData;  
    }  


2,发送邮件的“机关”

java 代码

MimeMessage msg =  new  MimeMessage(mailSession);  
msg.setFrom(new  InternetAddress( this .getSenderAddress()));  
msg.setSubject(this .getTitle());  
msg.setSentDate(new  Date());  
Address[] adds = InternetAddress.parse(getToAddress());  
msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);  
// 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)   
MimeMultipart mm = new  MimeMultipart( "related" );  
// 新建一个存放信件内容的BodyPart对象   
BodyPart mdp = new  MimeBodyPart();  
// 给BodyPart对象设置内容和格式/编码方式   
mdp.setContent(this .getContent(),  "text/html;charset=utf-8" );  
// 这句很重要,千万不要忘了   
mm.addBodyPart(mdp);  
  
// ---------图片处理开始!!!!!!!!!!!!!!!!   
mdp = new  MimeBodyPart();  
byte  bbb[] =  new   byte [ 1024  *  10 ];  
this .getClass().getClassLoader().getResourceAsStream( "notice.jpg" ).read(bbb);  
DataHandler dh = new  DataHandler( new  ByteArrayDataSource( this .getImageBytes( "notice.jpg" ), "application/octet-stream" ));  
mdp.setDataHandler(dh);  
// 加上这句将作为附件发送,否则将作为信件的文本内容   
mdp.setFileName("1.jpg" );  
mdp.setHeader("content-id" ,  "<IMG1>" );  
// 将含有附件的BodyPart加入到MimeMultipart对象中   
mm.addBodyPart(mdp);  
  
// 把mm作为消息对象的内容   
msg.setContent(mm); 



3,一个实际应用的完整代码
要求根据一个格式文件和模版,发一封漂亮的邮件,所以需要用到HTML格式来发送邮件。不多说了,看代码吧!

java 代码

import  java.io.ByteArrayOutputStream;  
import  java.io.File;  
import  java.io.FileReader;  
import  java.io.IOException;  
import  java.io.InputStream;  
import  java.util.Date;  
import  java.util.HashMap;  
import  java.util.Map;  
import  java.util.Properties;  
import  javax.activation.DataHandler;  
import  javax.mail.Address;  
import  javax.mail.BodyPart;  
import  javax.mail.internet.InternetAddress;  
import  javax.mail.internet.MimeBodyPart;  
import  javax.mail.internet.MimeMessage;  
import  javax.mail.internet.MimeMultipart;  
import  javax.mail.util.ByteArrayDataSource;  
/** */ /**  
*  
* @author robin  
* @version $Revision: 1.4 $  
*/   
public   class  SendMailUtil {  
    private  String mailServerAddress;  
    private  String user;  
    private  String password;  
    private  String toAddress;  
    private  String ccAddress;  
    private  String title;  
    private  String content;  
    private   boolean  isHtml =  true ;  
    private  Map attachmentFiles =  null ;  
    private  String senderAddress;  
  
    private   byte [] getImageBytes(String file) {  
        byte [] myData =  null ;  
        InputStream input = getClass().getClassLoader().getResourceAsStream(file);  
        try  {  
            ByteArrayOutputStream byteArray = new  ByteArrayOutputStream();  
            int  ch =  0 ;  
            while  ((ch = input.read()) != - 1 ) {  
                byteArray.write(ch);  
            }  
            // System.out.println(byteArray.size());   
            myData = byteArray.toByteArray();  
            // System.out.println(myData.length);   
        } catch  (Exception e) {  
            e.printStackTrace();  
        }  
        return  myData;  
    }  
  
    public   void  sendMail()  throws  Exception {  
        Properties pos = new  Properties();  
        pos.put("mail.smtp.host" ,  "10.5.1.1" );  
        javax.mail.Session mailSession = javax.mail.Session.getInstance(pos,null );  
        MimeMessage msg = new  MimeMessage(mailSession);  
        msg.setFrom(new  InternetAddress( this .getSenderAddress()));  
        msg.setSubject(this .getTitle());  
        msg.setSentDate(new  Date());  
        Address[] adds = InternetAddress.parse(getToAddress());  
        msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);  
        // 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)   
        MimeMultipart mm = new  MimeMultipart( "related" );  
        // 新建一个存放信件内容的BodyPart对象   
        BodyPart mdp = new  MimeBodyPart();  
        // 给BodyPart对象设置内容和格式/编码方式   
        mdp.setContent(this .getContent(),  "text/html;charset=utf-8" );  
        // 这句很重要,千万不要忘了   
        mm.addBodyPart(mdp);  
  
        // ---------图片处理开始!!!!!!!!!!!!!!!!   
        mdp = new  MimeBodyPart();  
        byte  bbb[] =  new   byte [ 1024  *  10 ];  
        this .getClass().getClassLoader().getResourceAsStream( "notice.jpg" ).read(bbb);  
        DataHandler dh = new  DataHandler( new  ByteArrayDataSource( this .getImageBytes( "notice.jpg" ),  "application/octet-stream" ));  
        mdp.setDataHandler(dh);  
        // 加上这句将作为附件发送,否则将作为信件的文本内容   
        mdp.setFileName("1.jpg" );  
        mdp.setHeader("content-id" ,  "<IMG1>" );  
        // 将含有附件的BodyPart加入到MimeMultipart对象中   
        mm.addBodyPart(mdp);  
        // ---------图片处理结束!!!!!!!!!!!!!!!!   
  
        // 把mm作为消息对象的内容   
        msg.setContent(mm);  
        msg.saveChanges();  
        javax.mail.Transport transport = mailSession.getTransport("smtp" );  
        transport.connect();  
        transport.sendMessage(msg, msg.getAllRecipients());  
        transport.close();  
    }  
  
    public  String getCcAddress() {  
        return  ccAddress;  
    }  
  
    public  String getContent() {  
        if  (content ==  null ) {  
            return   "" ;  
        } else  {  
            return  content;  
        }  
    }  
  
    public  String getMailServerAddress() {  
        return   "10.5.1.1" ;  
    }  
  
    public  String getUser() {  
        if  (user ==  null  || user.equals( "" )) {  
            user = "" ;  
        }  
        return  user;  
    }  
  
    public  String getPassword() {  
        if  (password ==  null  || password.equals( "" )) {  
            password = "" ;  
        }  
        return  password;  
    }  
  
    public  String getTitle() {  
        if  (title ==  null ) {  
            return   "" ;  
        } else  {  
            return  title;  
        }  
    }  
  
    public  String getToAddress() {  
        return  toAddress;  
    }  
  
    public   boolean  isHtml() {  
        return  isHtml;  
    }  
  
    public   void  setCcAddress(String ccAddress) {  
        this .ccAddress = ccAddress;  
    }  
  
    public   void  setContent(String content) {  
        this .content = content;  
    }  
  
    public   void  setMailServerAddress(String mailServerAddress) {  
        this .mailServerAddress = mailServerAddress;  
    }  
  
    public   void  setUser(String user) {  
        this .user = user;  
    }  
  
    public   void  setPassword(String password) {  
        this .password = password;  
    }  
  
    public   void  setTitle(String title) {  
        this .title = title;  
    }  
  
    public   void  setToAddress(String toAddress) {  
        this .toAddress = toAddress;  
    }  
  
    public   void  setIsHtml( boolean  isHtml) {  
        this .isHtml = isHtml;  
    }  
  
    public   void  setAttachmentFiles(Map attachmentFiles) {  
        this .attachmentFiles = attachmentFiles;  
    }  
  
    public  Map getAttachmentFiles() {  
        return  attachmentFiles;  
    }  
  
    public   void  setHtml( boolean  isHtml) {  
        this .isHtml = isHtml;  
    }  
  
    public  String getSenderAddress() {  
        return  senderAddress;  
    }  
  
    public   void  setSenderAddress(String senderAddress) {  
        this .senderAddress = senderAddress;  
    }  
  
    public  String readMailTemplate(String year, String season) throws  IOException {  
        ClassLoader loder = this .getClass().getClassLoader();  
        InputStream is = loder.getResourceAsStream("t.html" );  
        byte [] buf =  new   byte [ 1024  *  5 ];  
        is.read(buf);  
        String t = new  String(buf,  "utf-8" );  
        t = t.replaceFirst("#year" , year);  
        t = t.replaceFirst("#season" , season);  
        // System.out.println(t);   
        return  t;  
    }  
  
    public   static   void  sendNoticeMail(String title, String year, String season,String sender, File f) {  
        SendMailUtil logic = new  SendMailUtil();  
        try  {  
            logic.setTitle(title);  
            // logic.setMailServerAddress("10.5.1.1");   
            String temp = logic.readMailTemplate(year, season);  
            logic.setSenderAddress(sender);  
            FileReader fr = new  FileReader(f);  
  
            char [] ch =  new   char [ new  Long(f.length()).intValue()];  
            fr.read(ch);  
            StringBuffer sb = new  StringBuffer( new  Long(f.length()).intValue());  
            for  ( int  i =  0 ; i < ch.length; i++) {  
                sb.append(ch[i]);  
            }  
            String[] all = sb.toString().split("\n" );  
  
            // System.out.println(sb.toString());   
            for  ( int  i =  0 ; i < all.length; i++) {  
                if  (all[i].equals( "" )) {  
                    continue ;  
                }  
                String t = temp;  
                String[] item = all[i].split("," );  
                logic.setToAddress(item[2 ]);  
                // 处理内容   
                t = t.replaceFirst("#name" , item[ 1 ] +  "("  + item[ 0 ] +  ")" );  
                t = t.replaceAll("#total" , item[ 3 ]);  
                t = t.replaceFirst("#tax" , item[ 4 ]);  
                t = t.replaceFirst("#actualTotal" , item[ 5 ]);  
                logic.setContent(t);  
                logic.sendMail();  
            }  
        } catch  (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics