天天看點

javaMail實作多使用者發送

package com.cn.javamail;

import java.util.Date;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.Message.RecipientType;

import javax.mail.Authenticator;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class Demo2 {

public static void main(String[] args) throws Exception{

//定一個Properties對象,來設定伺服器環境資訊

Properties props=new Properties();

//設定要與伺服器會話要進行身份認證

props.setProperty("mail.smtp.auth", "true");

//定義郵件傳輸的協定是方式

props.setProperty("mail.transport.protocol", "smtp");

//設定伺服器的主機

   props.setProperty("mail.host", "smtp.sina.com");

Session session=Session.getInstance(props,

new Authenticator() {

     //發件人郵箱的使用者民、密碼

 private String userName="XXXXXX";

     private String password="XXXXX";

     protected PasswordAuthentication getPasswordAuthentication()

     {

     return new PasswordAuthentication(userName, password);

     }

}

);

session.setDebug(true);

//建立一個郵件對象,用于建立一份郵件和解析郵件

Message msg=new MimeMessage(session);

msg.setFrom(new InternetAddress("[email protected]"));

msg.setSubject("多人發送郵件測試");

//msg.setText("XXXXXXXXXXXXXXXXXXXXXXXX--------XXXXXXXXXXXXXXXXXXXXXXXXXXXX");

msg.setContent("<span style='color:red'>XXXXXXXXXXXXXXXXXXXXXXXX----中文----XXXXXXXXXXXXXXXXXXXXXXXXXXXX</span>", "text/html;charset=utf-8");

msg.setSentDate(new Date());

//設定收件人的類型,以及收件人郵箱

msg.setRecipients(RecipientType.TO, InternetAddress.parse("[email protected],[email protected]"));

//發送郵件

Transport.send(msg);

}

}