package mail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/** *//**
* 發(fā)送普通郵件,接受普通郵件 發(fā)送帶有附件的郵件,接收帶有附件的郵件 發(fā)送html形式的郵件,接受html形式的郵件 發(fā)送帶有圖片的郵件等做了一個總結(jié)。
*/
public class Test


{
// 郵箱服務(wù)器
private String host = "smtp.163.com";
// 這個是你的郵箱用戶名
private String username = "******";
// 你的郵箱密碼
private String password = "******";
private String mail_head_name = "this is head of this mail";

private String mail_head_value = "this is head of this mail";

private String mail_to = "zdw@live.cn";

private String mail_from = "*****@163.com";

private String mail_subject = "this is the subject of this test mail";

private String mail_body = "this is the mail_body of this test mail";

private String personalName = "我的郵件";

public Test()

{
}


/** *//**
* 此段代碼用來發(fā)送普通電子郵件
*/
public void send() throws Exception

{
try

{
Properties props = new Properties(); // 獲取系統(tǒng)環(huán)境
Authenticator auth = new Email_Autherticator(); // 進行郵件服務(wù)器用戶認證
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, auth);
// 設(shè)置session,和郵件服務(wù)器進行通訊。
MimeMessage message = new MimeMessage(session);
// message.setContent("foobar, "application/x-foobar"); // 設(shè)置郵件格式
message.setSubject(mail_subject); // 設(shè)置郵件主題
message.setText(mail_body); // 設(shè)置郵件正文
message.setHeader(mail_head_name, mail_head_value); // 設(shè)置郵件標題
message.setSentDate(new Date()); // 設(shè)置郵件發(fā)送日期
Address address = new InternetAddress(mail_from, personalName);
message.setFrom(address); // 設(shè)置郵件發(fā)送者的地址
Address toAddress = new InternetAddress(mail_to); // 設(shè)置郵件接收方的地址
message.addRecipient(Message.RecipientType.TO, toAddress);
Transport.send(message); // 發(fā)送郵件
System.out.println("send ok!");
} catch (Exception ex)

{
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}


/** *//**
* 用來進行服務(wù)器對用戶的認證
*/
public class Email_Autherticator extends Authenticator

{
public Email_Autherticator()

{
super();
}

public Email_Autherticator(String user, String pwd)

{
super();
username = user;
password = pwd;
}

public PasswordAuthentication getPasswordAuthentication()

{
return new PasswordAuthentication(username, password);
}
}

public static void main(String[] args)

{
Test sendmail = new Test();
try

{
sendmail.send();
} catch (Exception ex)

{
}
}

}

經(jīng)測試在126,163,sina上成功.