下面是一個發(fā)送簡單E-mail的例子。假設你的localhost已經連接到網絡。
// 文件名 SendEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail { public static void main(String [] args) { // 收件人電子郵箱 String to = "abcd@gmail.com"; // 發(fā)件人電子郵箱 String from = "web@gmail.com"; // 指定發(fā)送郵件的主機為 localhost String host = "localhost"; // 獲取系統(tǒng)屬性 Properties properties = System.getProperties(); // 設置郵件服務器 properties.setProperty("mail.smtp.host", host); // 獲取默認session對象 Session session = Session.getDefaultInstance(properties); try{ // 創(chuàng)建默認的 MimeMessage 對象 MimeMessage message = new MimeMessage(session); // Set From: 頭部頭字段 message.setFrom(new InternetAddress(from)); // Set To: 頭部頭字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: 頭部頭字段 message.setSubject("This is the Subject Line!"); // 設置消息體 message.setText("This is actual message"); // 發(fā)送消息 Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }
編譯并運行這個程序來發(fā)送一封簡單的E-mail:
$ java SendEmail Sent message successfully....
如果你想發(fā)送一封e-mail給多個收件人,那么使用下面的方法來指定多個收件人ID:
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
下面是對于參數的描述:
type:要被設置為TO, CC 或者BCC. 這里CC 代表抄送、BCC 代表秘密抄送y. 舉例:Message.RecipientType.TO
addresses: 這是email ID的數組。在指定電子郵件ID時,你將需要使用InternetAddress()方法。
2015職稱計算機考試書PowerPoint2007中 .. 定價:¥45 優(yōu)惠價:¥42 更多書籍 | |
2015年全國職稱計算機考試教材(2007模 .. 定價:¥225 優(yōu)惠價:¥213 更多書籍 |