JavaMail操作的總結(1)

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- JavaMail操作的總結(1) (http://www.webasp.net/article/18/17343.htm)
-- 作者:未知
-- 發佈日期: 2005-04-06
在整理網友的文章的時候,發現一個javamail的總結,特此謝謝the_east_key,並且公佈給大家,希望對大家有做幫助,全文如下:
本文章對:
發送普通郵件,接受普通郵件
發送帶有附件的郵件,接收帶有附件的郵件
發送html形式的郵件,接受html形式的郵件
[b[發送帶有圖片的郵件[/b]等做了一個總結。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;


public String host="smtp.163.com";
public String username="abcdefg";
public String password="abcdefg";
public String mail_head_name="this is head of this mail";
public String mail_head_value="this is head of this mail";
public String mail_to="xyz@163.com";
public String mail_from="abcdefg@163.com";
public String mail_subject="this is the subject of this test mail";
public String mail_body="this is the mail_body of this test mail";
//此段代碼用來發送普通電子郵件
void jButton1_actionPerformed(ActionEvent e) {
try
{
Properties props = new Properties();//獲取系統環境
Authenticator auth = new Email_Autherticator();//進行郵件服務器用戶認證

props.put("mail.smtp.host",host);
props.put("mail.smtp.auth","true");
Session session = Session.getDefaultInstance(props,auth);
//設置session,和郵件服務器進行通訊。
MimeMessage message = new MimeMessage(session);
message.setContent("Hello","text/plain");//設置郵件格式
message.setSubject(mail_subject);//設置郵件主題
message.setText(mail_body);//設置郵件正文
message.setHeader(mail_head_name,mail_head_value);//設置郵件標題
message.setSentDate(new Date());//設置郵件發送日期

Address address = new InternetAddress(mail_from,"sunxiaoming");
message.setFrom(address); //設置郵件發送者的地址

//如果要對郵件發送者進行多個參數的設置,可以用以下語句
// Address address[] = {new InternetAddress("sunxm@oaklet.co.jp","sunxmatoaklet"),new InternetAddress("firstsxm@hotmail.com","sunxmathotmail")};
// message.addFrom(address);

Address toAddress = new InternetAddress(mail_to);//設置郵件接收方的地址
message.addRecipient(Message.RecipientType.TO,toAddress);
// Address ccAddress = new InternetAddress("firstsxm@hotmail.com");//設置郵件抄送者的地址
// message.addRecipient(Message.RecipientType.CC,ccAddress);


Transport.send(message);//發送郵件
/* // to get a specific instance from the session for your protocol.pass along the username and password
// (blank if unnecessary).send the message,and close the connection;
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host,username,password);
transport.sendMessage(message,message.getAllRecipients());
transport.close();
*/
System.out.println("send ok!");
}
catch(Exception ex)
{
System.out.println("faild"+ex);
}
}

 

webasp.net