使用JAVAMAIL發郵件的一個例子

來源:互聯網
上載者:User
發郵件 首先引入j2ee的包路徑到ClassPath,已經安裝Jbuilder的可以在它的安裝路徑lib目錄下找
到mail.jar,activation.jar,將這兩個包加入系統的環境變數,那麼即使不用JBuilder開發的話也可以
使用了.

程式:

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
* <p>Title: 簡易MailBean</p>
* <p>Description: 提供簡便的Mail發送功能(/p>
* <p>Copyright: Copyright (c) 2003</p>
* @version 1.0
*/

class ExtendString {
public ExtendString() {
}
/**
去掉字串兩端的空白字元,並將字串轉化為中國的標準字元gb2312的字串.
*/
public String CS(String str) { //去掉字串2端的空白字元
try {
if (str == null)
return "";
str = str.trim();
if (str == null)
return "";
str = new String(str.getBytes("8859_1"), "GBK");
}
catch (Exception e) {
System.out.println(e);
}
return str;
}

}

public class SendMail
{
private String errMsg = "";
private ExtendString ExStr = new ExtendString();

private String sender = "";//寄件者地址
private String smtpHost = "";//郵件發送伺服器(smtp)
private String user = ""; //登入使用者名稱
private String password = "";//登入密碼

private String subject = "";//mail主題

public SendMail()
{
this.setPropertiesAttri();
}

private void setPropertiesAttri()
{
try
{
InputStream is = getClass().getResourceAsStream("MailServer.properties");
Properties prop = new Properties();
prop.load(is);

this.setSmtpHost(prop.get("SmtpHost").toString());
this.setUser(prop.get("User").toString());
this.setPassword(prop.get("Password").toString());
this.setSender(prop.get("Sender").toString());
this.setSubject(ExStr.CS(prop.get("Subject").toString()));
}
catch(Exception ex)
{
System.err.println("ex1 in sendmail.java:"+ex.toString());
}
}
/** 設定寄件者地址 */

public void setSender(String sender)
{
this.sender = sender;
}

public String getSender()
{
return sender;
}

/** 設定郵件發送伺服器(smtp) */
public void setSmtpHost(String smtpHost) {this.smtpHost = smtpHost;}
public String getSmtpHost() {return smtpHost;}

/** 設定登入使用者名稱 */
public void setUser(String user)
{
this.user = user;
}
public String getUser()
{
return user;
}

/** 設定登入密碼 */
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}

/** 設定mail主題 */
public void setSubject(String subject)
{
this.subject = subject;
}
public String getSubject()
{
return subject;
}

/**
* 使用smtp發送郵件 主程式
* @throws MessagingException mail發送失敗
*/
public void smtp(String receiver,String content) throws MessagingException
{
if (smtpHost == null) throw new MessagingException("smtpHost not found");
if (user == null) throw new MessagingException("user not found");
if (password == null) throw new MessagingException("password not found");

Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);//設定smtp主機
properties.put("mail.smtp.auth", "true");//使用smtp身分識別驗證

Session session = Session.getDefaultInstance(properties,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, password);
}
});

//獲得郵件會話對象
MimeMessage mimeMsg = new MimeMessage(session);//建立MIME郵件對象
if (sender != null)//設定寄件者地址
{
mimeMsg.setFrom(new InternetAddress(sender));
}
if (receiver != null)//設定收件者地址
{
mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver));
}
if (subject != null)//設定郵件主題
{
mimeMsg.setSubject(subject, "GBK");
}
MimeBodyPart part = new MimeBodyPart();//mail內容部分
part.setText(content == null ? "" : content, "GBK");

//設定郵件格式為html cqc
part.setContent(content.toString(),"text/html;charset=GBK");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(part);//在 Multipart 中增加mail內容部分
mimeMsg.setContent(multipart);//增加 Multipart 到資訊體
mimeMsg.setSentDate(new Date());//設定發送日期
Transport.send(mimeMsg);//發送郵件
}

/** 解析地址集合字串 */
private InternetAddress[] parse(String addressSet) throws AddressException
{
ArrayList list = new ArrayList();
StringTokenizer tokens = new StringTokenizer(addressSet, ";");
while (tokens.hasMoreTokens())
{
list.add(new InternetAddress(tokens.nextToken().trim()));
}
InternetAddress[] addressArray = new InternetAddress[list.size()];
list.toArray(addressArray);
return addressArray;
}

/**
* 供外部調用的介面
*/

public boolean sendMails(String mail,String content)
{
int mailLen = 0 ;
int contentLen= 0;
if (mail == null||content==null)
{
return false;
}

try
{
this.smtp(mail,content);
}
catch(Exception ex)
{
System.err.println("ex2 in sendmail.java:"+ex.toString());
}

return true;
}

public static void main (String[] args)
{
SendMail mail = new SendMail();
String email = "feng_lei@ecfounder.com;ladofwind@163.com";
String content = "帳號:123 密碼:123 <br/>感謝您註冊!<br/><a href='http://www.xxxx.com.cn' target='_blank'>www.xxxx.com.cn</a><br/>此致<br/>xxxx <br/>即日";
try
{
mail.sendMails(email,content);
}
catch (Exception ex)
{
System.err.println("ex33:"+ex.toString());
}
}


}

編譯通過後,在class檔案的目錄下建立一個文字檔MailServer.properties,
格式:
SmtpHost=smtp.163.com
User=user
Password=pwd
Sender=csdn@csdn.com
Subject=Hello


運行程式即可實現郵件發送!




聯繫我們

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