JAVA發送HTML格式郵件.

來源:互聯網
上載者:User

 

package com.awu;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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 SendHTMLMail ...{

 /** *//**
  * @param args
  */
 public static void main(String[] args) ...{
  String tto="love_wuzhou520@163.com";
  String ttitle="發送HTML格式郵件";
  String tcontent="<table border='1' bgColor='red'><tr><td>發送一個表格</td></tr></table>";//HTML代碼
  Properties props=new Properties();
  props.put("mail.smtp.host","smtp.163.com");
  props.put("mail.smtp.auth","true");
  Session s=Session.getInstance(props);
  s.setDebug(true);

  MimeMessage message=new MimeMessage(s);

//  給訊息對象設定寄件者/收件者/主題/發信時間
  try...{
  InternetAddress from=new InternetAddress("love_wuzhou520@163.com");
  message.setFrom(from);
  InternetAddress to=new InternetAddress(tto);
  message.setRecipient(Message.RecipientType.TO,to);
  message.setSubject(ttitle);
  message.setSentDate(new Date());


//  給訊息對象設定內容
  BodyPart mdp=new MimeBodyPart();//建立一個存放信件內容的BodyPart對象
  mdp.setContent(tcontent,"text/html;charset=gb2312");//給BodyPart對象設定內容和格式/編碼方式
  Multipart mm=new MimeMultipart();//建立一個MimeMultipart對象用來存放BodyPart對
//  象(事實上可以存放多個)
  mm.addBodyPart(mdp);//將BodyPart加入到MimeMultipart對象中(可以加入多個BodyPart)
  message.setContent(mm);//把mm作為訊息對象的內容

  message.saveChanges();
  Transport transport=s.getTransport("smtp");
  transport.connect("smtp.163.com","love_wuzhou520","郵件密碼");
  transport.sendMessage(message,message.getAllRecipients());
  transport.close();
  System.out.println("發送成功!");
  }catch (Exception e) ...{
   e.printStackTrace();
   // TODO: handle exception
  }


 }

}
 

 

 

需要J2EE(1.4)裡的mail.jar包

相關文章

聯繫我們

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