1. 程式人生 > >發郵件包含附件

發郵件包含附件

public class SendMailService {

    public void createTs(EmailDto emailDto) throws MessagingException, IOException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");

        //使用JavaMail傳送郵件的5個步驟
        
        //1、建立session,並開啟debug模式,這樣就可以檢視到程式傳送Email的執行狀態
        Session session = Session.getInstance(prop);
        session.setDebug(true);
        
        //2、通過session得到transport物件
        Transport ts = session.getTransport();
        
        //3、連上郵件伺服器
        ts.connect("smtp.qq.com", "{你的使用者名稱}", "{你的smtp校驗碼}");
        
        //4、建立郵件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailDto.getSender()));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailDto.getReceiver()));
        message.setSubject(emailDto.getSubject());
        
        //建立郵件正文,為了避免郵件正文中文亂碼問題,需要使用charset=UTF-8指明字元編碼
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(emailDto.getContent(), "text/html;charset=UTF-8");
        
        //建立郵件附件
        File f = transfer(emailDto.getFile());
        MimeBodyPart attach = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(f);
        DataHandler dh = new DataHandler(fds);
        attach.setDataHandler(dh);
        attach.setFileName(MimeUtility.encodeText(fds.getName()));
            
        //建立容器描述資料關係
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(text);
        mp.addBodyPart(attach);
        mp.setSubType("mixed");
        message.setContent(mp);
        message.saveChanges();
        
        //5、傳送郵件,並刪除臨時檔案
        ts.sendMessage(message, message.getAllRecipients());
        File del = new File(f.toURI());
        del.delete();
        ts.close();
    }

    private File transfer(MultipartFile file) throws IOException {
        InputStream ins = file.getInputStream();
        File f = new File(Objects.requireNonNull(file.getOriginalFilename()));
        inputStreamToFile(ins, f);
        return f;
    }

    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while (-1 != (bytesRead = ins.read(buffer, 0, 8192))) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
@Data
public class EmailDto {
    //正文
    private String content;
    //標題
    private String subject;
    //發件人
    private String sender;
    //收件人
    private String receiver;
    private MultipartFile file;
}