javamail 發送 帶附件的 html郵件

來源:互聯網
上載者:User

/**
 *
 */
package com.tsts.oa.mail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
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;

/**
 * @author sunyanan
 *
 */
public class SendHelper {

 public static void send() throws Exception {
  Properties prop = new Properties();
  prop.put("mail.smtp.host", "smtp.126.com");
  prop.put("mail.smtp.auth", "true");
  
  Session session =  Session.getDefaultInstance(prop, (new SendHelper()).new AT());
  
  session.setDebug(true);
  MimeMessage message = new MimeMessage(session);
  
  message.setFrom(new InternetAddress("sunyanan8@126.com"));
  message.setRecipient(Message.RecipientType.TO, new InternetAddress("sunyanan8@126.com"));
  message.setSubject("主題");
  
  BodyPart bodyPart = new MimeBodyPart();
  bodyPart.setContent("<a href=/"#/">內容</a>", "text/html;charset=gbk");
  
  BodyPart filePart = new MimeBodyPart();
  FileDataSource ds = new FileDataSource("c://a.txt"); // a.txt為附件地址,附件和發郵件程式位於一台伺服器
  filePart.setDataHandler(new DataHandler(ds));
  
  Multipart part = new MimeMultipart();
  part.addBodyPart(bodyPart);
  part.addBodyPart(filePart);
  message.setContent(part);
  
  Transport.send(message);
  
 }

 /**
  * @param args
  */
 public static void main(String[] args) throws Exception {
  send();

 }
 
 class AT extends Authenticator {

  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
   // TODO Auto-generated method stub
   return new PasswordAuthentication("sunyanan8@126.com", "xxxxxxxxxx");
  }
 }

}

 

這樣就好說多了,如果是上傳本地附件 自己增加一個上傳功能 就好了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.