Java Mail 發送帶有附件的郵件

來源:互聯網
上載者:User

標籤:訊息   javamail   .net   str   utf-8   otf   hand   密碼   exception   

1、小編用的是163郵箱發送郵件,所以要先登入163郵箱開啟POP3/SMTP/IMAP服務方法:

 

2、下載所需的java-mail 包

https://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/

 

3、貼上代碼

package javamail;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Authenticator;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class sendMail {/** * 建立郵件資訊 * @param session * @param fromAccount * @param toAccount * @param sourcePath xml檔案目錄   e.g. xml * @param zipPath   zip檔案目錄  e.g. zip/person.zip */    public static void CreateMessage(final Session session, final String fromAccount, final String toAccount,final String sourcePath,final String zipPath){        try{            final String subjectStr="聖誕節快樂";//主題            final StringBuffer contentStr=new StringBuffer();//內容            contentStr.append("<h2>Dear Friends,</h2><br/>");            contentStr.append("Christmas is coming up soon. <br/> Wish you lots of love, joy &happiness. happy christmas.");            contentStr.append("<h3>Regards,</h3>").append("<h3>ZHBIT College</h3>");           //建立預設的 MimeMessage 對象           final MimeMessage message = new MimeMessage(session);           //Set From: 頭部頭欄位           message.setFrom(new InternetAddress(fromAccount));           //Set To: 頭部頭欄位           message.addRecipient(Message.RecipientType.TO,                                    new InternetAddress(toAccount));           //Set Subject: 頭部頭欄位           message.setSubject(subjectStr);          //建立訊息部分           final BodyPart messageBodyPart = new MimeBodyPart();           //訊息           messageBodyPart.setContent(contentStr.toString(),"text/html;charset=UTF-8");           //建立多重訊息           final Multipart multipart = new MimeMultipart();           //設定簡訊部分           multipart.addBodyPart(messageBodyPart);           //為郵件添加多個附件           MimeBodyPart attachment = null;           final File source = new File(sourcePath);           if (!source.exists()) {               System.out.println(sourcePath + " not exists");               return;           }           final File[] files = source.listFiles();           for (final File f : files) {               attachment = new MimeBodyPart();               final String filePath =f.getPath();               //根據附件檔案建立檔案資料來源               final DataSource ds = new FileDataSource(filePath);               attachment.setDataHandler(new DataHandler(ds));               //為附件設定檔案名稱               attachment.setFileName(ds.getName());               multipart.addBodyPart(attachment);           }           //添加zip附件           attachment = new MimeBodyPart();           //根據附件檔案建立檔案資料來源           final DataSource ds = new FileDataSource(zipPath);           attachment.setDataHandler(new DataHandler(ds));           //為附件設定檔案名稱           attachment.setFileName(ds.getName());           multipart.addBodyPart(attachment);           // 發送完整訊息           message.setContent(multipart);           // 發送訊息           Transport.send(message);        }catch (final MessagingException mex) {           mex.printStackTrace();        }    }/** * 將源檔案目錄下的所有檔案打包成zip檔案 * @param sourceFilePath  e.g. xml * @param zipFilePath   e.g. zip * @param fileName   e.g. person * @return 返回產生的zip檔案目錄  e.g. zip/person.zip */    public static String tozip(final String sourceFilePath, final String zipFilePath,            final String fileName) {        final File sourceFile = new File(sourceFilePath);        FileInputStream fis = null;        BufferedInputStream bis = null;        FileOutputStream fos = null;        ZipOutputStream zos = null;        final String createZipPath=zipFilePath+ "/" + fileName+ ".zip";        if(!sourceFile.exists()){            System.out.println("待壓縮的檔案目錄:" + sourceFilePath + "不存在");        } else {            try {                final File zipFile = new File(createZipPath);                final File[] sourceFiles = sourceFile.listFiles();                if(null == sourceFiles || sourceFiles.length < 1) {                    System.out.println("待壓縮的檔案目錄:" + sourceFilePath + " 裡面不存在檔案,無需壓縮");                }else{                    fos = new FileOutputStream(zipFile);                    zos = new ZipOutputStream(new BufferedOutputStream(fos));                    final byte[] bufs = new byte[1024*10];                    for(int i=0;i<sourceFiles.length;i++) {                        // 建立ZIP實體,並添加進壓縮包                        final ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());                        zos.putNextEntry(zipEntry);                        // 讀取待壓縮的檔案並寫進壓縮包裡                        fis = new FileInputStream(sourceFiles[i]);                        bis = new BufferedInputStream(fis,1024*10);                        int read = 0;                        while((read=bis.read(bufs, 0, 1024*10)) != -1) {                            zos.write(bufs, 0, read);                        }                    }                }            } catch (final FileNotFoundException e) {                e.printStackTrace();                throw new RuntimeException(e);            } catch (final IOException e) {                e.printStackTrace();                throw new RuntimeException(e);            } finally {                try {                    if (null != bis) {                        bis.close();                    }                    if (null != zos) {                        zos.close();                    }                } catch (final IOException e) {                    e.printStackTrace();                    throw new RuntimeException(e);                }            }        }        return createZipPath;    }    public static void main(final String[] args) {        //收件者電子郵箱        final String toAccount = "********@qq.com";        //寄件者的 郵箱 和 密碼        final String fromAccount = "**********@163.com";        final String fromPassword = "**********";        //指定發送郵件的主機        final String host = "smtp.163.com";        //建立參數配置, 擷取系統屬性        final Properties properties = System.getProperties();        properties.setProperty("mail.transport.protocol", "smtp");        properties.setProperty("mail.smtp.host", host);        properties.put("mail.smtp.auth", "true");        //根據配置建立會話對象,擷取預設session對象        final Session session = Session.getDefaultInstance(properties,new Authenticator(){          @Override            public PasswordAuthentication getPasswordAuthentication()              {               return new PasswordAuthentication(fromAccount, fromPassword); //寄件者郵件使用者名、密碼              }         });        session.setDebug(true);        final String xmlPath="xml";        final String zipPath=tozip(xmlPath,"zip","person");        CreateMessage(session,fromAccount,toAccount,xmlPath,zipPath);    }}

 

4、收到郵件

 

Java Mail 發送帶有附件的郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.