java發送郵件可帶附件,以及發送網頁等

來源:互聯網
上載者:User

所需jar包(javamail.jar和activation.jar共366K)如下:
http://www.blackswansoft.com/songhaikang/files/myfile/Java%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6%E5%B8%B8%E7%94%A8%E5%8C%85.rar

更多熱點的Java文章請到黑天鵝軟體網站的“推薦文章”版塊查看
網站地址如下:http://www.BlackSwanSoft.com/

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailSend {

/**
* 更強大的發送郵件案例
* 發件方式枚舉
* @author lanxj
*/
public enum SendTypeEnum{
TO(0,"發件方式 - 普通發送"),CS(1,"發件方式 - 抄送"),MCS(2,"發件方式 - 密件副本");
private int type;
private String description;
SendTypeEnum(int type,String desc){
this.type=type;
this.description=desc;
}
public int intValue(){
return this.type;
}
public String getDescription(){
return this.description;
}
}

/** 郵件相關資訊 - SMTP 伺服器 */
private String smtpHost = null;
/** 郵件相關資訊 - 郵件使用者名 */
private String username = null;
/** 郵件相關資訊 - 密碼 */
private String password = null;
/** 郵件相關資訊 - 寄件者郵件地址 */
private String fromAddress = null;
/** 郵件相關資訊 - 郵件主題 */
private String subject = "";
/** 郵件相關資訊 - 郵件發送地址 */
private Address[] toAddress = null;
/** 郵件相關資訊 - 郵件抄送地址 */
private Address[] csAddress = null;
/** 郵件相關資訊 - 郵件密件副本地址 */
private Address[] mcsAddress = null;
/** 郵件相關資訊 - 郵件內文(複合結構) */
private MimeMultipart context = null;

public MailSend() {
context = new MimeMultipart();
}

/**
* 設定 SMTP 伺服器
* @param strSMTPHost 郵件伺服器名稱或 IP
* @param strUser 郵件使用者名
* @param strPassword 密碼
*/
public void setSMTP(String strSMTPHost, String strUser,
String strPassword) {
this.smtpHost = strSMTPHost;
this.username = strUser;
this.password = strPassword;
}

/**
* 設定郵件發送地址
* @param strFromAddress 郵件發送地址
*/
public void setFromAddress(String strFromAddress) {
this.fromAddress = strFromAddress;
}

/**
* 設定郵件目的地址
* @param strAddress 郵件目的地址清單, 不同的地址可用;號分隔
* @param iAddressType 郵件發送方式 (SendTypeEnum.TO 0, SendTypeEnum.CS 1, SendTypeEnum.MCS 2) 枚舉已在本類定義
* @throws AddressException
*/
public void setAddress(String strAddress, SendTypeEnum iAddressType) throws AddressException {
if (iAddressType==SendTypeEnum.TO) {
ArrayList alAddress = splitStr(strAddress, ';');
toAddress = new Address[alAddress.size()];
for (int i = 0; i < alAddress.size(); i++) {
toAddress[i] = new InternetAddress( (String) alAddress.get(i));
}
}else if (iAddressType==SendTypeEnum.CS) {
ArrayList alAddress = splitStr(strAddress, ';');
csAddress = new Address[alAddress.size()];
for (int i = 0; i < alAddress.size(); i++) {
csAddress[i] = new InternetAddress( (String) alAddress.get(i));
}
}else if (iAddressType==SendTypeEnum.MCS) {
ArrayList alAddress = splitStr(strAddress, ';');
mcsAddress = new Address[alAddress.size()];
for (int i = 0; i < alAddress.size(); i++) {
mcsAddress[i] = new InternetAddress( (String) alAddress.get(i));
}
}
}

/**
* 設定郵件主題
* @param strSubject 郵件主題
*/
public void setSubject(String strSubject) {
this.subject = strSubject;
}

/**
* 設定郵件文本本文
* @param strTextBody 郵件文本本文
* @throws MessagingException
*/
public void setContext(String strTextBody) throws MessagingException {
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setText(strTextBody, "GBK");
context.addBodyPart(mimebodypart);
}

/**
* 設定郵件超文本本文
* @param strHtmlBody 郵件超文本本文
* @throws MessagingException
*/
public void setHtmlContext(String strHtmlBody) throws MessagingException {
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setDataHandler(new DataHandler(strHtmlBody, "text/html;charset=GBK"));
context.addBodyPart(mimebodypart);
}

/**
* 設定郵件內文外部連結 URL, 信體中將包含連結所指向的內容
* @param strURLAttachment 郵件內文外部連結 URL
* @throws MessagingException
* @throws MalformedURLException
*/
public void setURLAttachment(String strURLAttachment) throws
MessagingException, MalformedURLException {
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setDataHandler(new DataHandler(new URL(strURLAttachment)));
context.addBodyPart(mimebodypart);
}

/**
* 設定郵件附件
* @param strFileAttachment 檔案的全路徑
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void setFileAttachment(String strFileAttachment) throws MessagingException, UnsupportedEncodingException {
File path = new File(strFileAttachment);
if (!path.exists() || path.isDirectory()) {
return;
}
String strFileName = path.getName();
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setDataHandler(new DataHandler(new FileDataSource(
strFileAttachment)));
// modified by zord @ 2003/6/16 to support Chinese File Name
// mimebodypart.setFileName(strFileName);
mimebodypart.setFileName(MimeUtility.encodeText(strFileName));
// end of modify
context.addBodyPart(mimebodypart);
}

/**
* 主方法:郵件發送(一次發送多個地址, 優點速度快, 但是有非法郵件地址時將中斷髮送操作)
* 前提條件{
* setSMTP();【必選】
* setFromAddress();【必選】
* setAddress();【必選】
* setSubject();【必選】
* set*Context();【必選】
* set*Attachment();【可選】
* }
* @throws MessagingException
*/
@SuppressWarnings("static-access")
public void sendBatch() throws MessagingException {
Properties properties = new Properties();
properties.put("mail.smtp.host", this.smtpHost);
properties.put("mail.smtp.auth", "true");//必須
Session session = Session.getInstance(properties, new Authenticator(){
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){//這個很重要,當今mail伺服器大多都是通過認證才能發信的
return new javax.mail.PasswordAuthentication(MailSend.this.username, MailSend.this.password);
}
});
MimeMessage mimemessage = new MimeMessage(session);
mimemessage.setFrom(new InternetAddress(this.fromAddress));
if (toAddress != null) {
mimemessage.addRecipients(javax.mail.Message.RecipientType.TO, this.toAddress);
}
if (csAddress != null) {
mimemessage.addRecipients(javax.mail.Message.RecipientType.CC, this.csAddress);
}
if (mcsAddress != null) {
mimemessage.addRecipients(javax.mail.Message.RecipientType.BCC, this.mcsAddress);
}
mimemessage.setSubject(this.subject);
mimemessage.setContent(this.context);
mimemessage.setSentDate(new Date());

/*發送方式一
Transport transport = session.getTransport("smtp");
transport.connect(this.smtpHost, this.username, this.password);
transport.send(mimemessage);
*/
//發送方式二
Transport.send(mimemessage);

System.out.println("已向下列郵箱發送了郵件");
showAddress(toAddress,csAddress,mcsAddress);
}

/**
* 顯示所有的收件者地址資訊
* @param addresses
*/
private static void showAddress(Address[] ... addresses){
if (addresses != null) {
for (int i = 0; i < addresses.length; i++) {
if(addresses[i]!=null){
for (int j = 0; j < addresses[i].length; j++) {
System.out.println(addresses[i][j]);
}
}
}
}
}

/**
* 將字串分割成字串集合
* @param str 字串
* @param sp 分隔字元
* @return
*/
private static ArrayList splitStr(String str,char sp){
ArrayList retu=new ArrayList();
String []res=str.split(""+sp);
for (String s : res) {
retu.add(s);
}
return retu;
}

public static void main(String[] args) {
try {
MailSend mail=new MailSend();
mail.setFromAddress("lanxj@sh-stt.com");
mail.setSMTP("smtp.163.com","nanjifengchen@163.com","password");

mail.setAddress("nanjifengchen@163.com;songhaikang@163.com",SendTypeEnum.TO);
// mail.setAddress("lanxj@sh-stt.com", SendTypeEnum.CS);
// mail.setAddress("694626525@qq.com", SendTypeEnum.MCS);
mail.setSubject("郵件發送測試");//標題
// mail.setContext("如有打擾,請見諒,謝謝!");//內容
// mail.setHtmlContext("如有打擾,請見諒,謝謝!");//支援html
try{
mail.setFileAttachment("D:\temp\tnsnames_sh.ora");//本地附件
mail.setURLAttachment("http://static.tieba.baidu.com/tb/img/2010120801.jpg");//網路檔案
// mail.setURLAttachment("http://static.tieba.baidu.com/tb/editor/images/jd/j_0017.gif");
mail.setURLAttachment("http://tieba.baidu.com");//引用網頁
}catch (Exception e) {
System.out.println("附件發送異常");
}
mail.sendBatch();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}

}

相關文章

聯繫我們

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