一.郵箱服務器的基本概念
郵件的客戶端:可以只安裝在電腦上(C/S)的也可以是網頁形式(B/S)的
郵件服務器:起到郵件的接受與推送的作用
郵件發送的協議:
協議:就是數據傳輸的約束
接受郵件的協議:POP3 、 IMAP
發送郵件的協議:SMTP
網易郵箱服務器地址:
pop.126.com
smtp.126.com
imap.126.com
郵件發送與接收的詳細過程
二,demo—做一個生日祝福定時發送
package beyond.mail;import java.util.Properties;import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;public class MailUtils {//email:郵件要發給誰(收件人)//subject:代表主題//emailMsg:郵件的內容public static void sendMail(String email, String subject,String emailMsg)throws AddressException, MessagingException {// 1.創建一個程序與郵件服務器會話對象 SessionProperties props = new Properties();props.setProperty("mail.transport.protocol", "SMTP");//發郵件的協議props.setProperty("mail.host", "localhost");//發送郵件的服務器地址props.setProperty("mail.smtp.auth", "true");// 指定驗證為true// 創建驗證器Authenticator auth = new Authenticator() {public PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("yan", "beyond");//發郵件的賬號驗證}};Session session = Session.getInstance(props, auth);// 2.創建一個Message,它相當于是郵件內容Message message = new MimeMessage(session);message.setFrom(new InternetAddress("yan@yy.com")); // 設置發送者message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者message.setSubject(subject);//設置郵件的主題// message.setText("這是一封激活郵件,請<a href='#'>點擊</a>");message.setContent(emailMsg, "text/html;charset=utf-8");// 3.創建 Transport用于將郵件發送Transport.send(message);}
}
package beyond.birthday;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DataSourceUtils {private static DataSource dataSource = new ComboPooledDataSource();private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();// 直接可以獲取一個連接池public static DataSource getDataSource() {return dataSource;}public static Connection getConnection() throws SQLException{return dataSource.getConnection();}// 獲取連接對象public static Connection getCurrentConnection() throws SQLException {Connection con = tl.get();if (con == null) {con = dataSource.getConnection();tl.set(con);}return con;}// 開啟事務public static void startTransaction() throws SQLException {Connection con = getCurrentConnection();if (con != null) {con.setAutoCommit(false);}}// 事務回滾public static void rollback() throws SQLException {Connection con = getCurrentConnection();if (con != null) {con.rollback();}}// 提交并且 關閉資源及從ThreadLocall中釋放public static void commitAndRelease() throws SQLException {Connection con = getCurrentConnection();if (con != null) {con.commit(); // 事務提交con.close();// 關閉資源tl.remove();// 從線程綁定中移除}}// 關閉資源方法public static void closeConnection() throws SQLException {Connection con = getCurrentConnection();if (con != null) {con.close();}}public static void closeStatement(Statement st) throws SQLException {if (st != null) {st.close();}}public static void closeResultSet(ResultSet rs) throws SQLException {if (rs != null) {rs.close();}}}
web.xml
<listener><listener-class>beyond.birthday.BirthdayListener</listener-class> </listener>
package beyond.birthday;public class Customer {private int id;private String username;private String password;private String realname;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getRealname() {return realname;}public void setRealname(String realname) {this.realname = realname;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}private String birthday;private String email;}
package beyond.birthday;import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;import javax.mail.MessagingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;import beyond.birthday.Customer;
import beyond.mail.MailUtils;public class BirthdayListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {//當web應用啟動開啟調動---功能在用戶的生日當前發送郵件Timer timer = new Timer();//開啟定時器,導util下的包timer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {//為當前生日用戶發郵件//1,獲得當前過生日的用戶SimpleDateFormat format = new SimpleDateFormat("MM-dd");//獲得當天的日期String currentDate = format.format(new Date());//currentDate----10-14QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());//根據當前的時間,從數據庫查詢今天過生日的用戶String sql = "select * from customer where birthday like ?";//寫SQL語句List<Customer> customerList = null;try {customerList = runner.query(sql, new BeanListHandler<Customer>(Customer.class),"%"+currentDate);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}//2,發郵件給當前過生日的用戶if(customerList!=null&&customerList.size()>0){for(Customer c :customerList){String emailMsg = "親愛的:" + c.getRealname() + ",生日快樂!";try {MailUtils.sendMail(c.getEmail(), "生日祝福", emailMsg);System.out.println(c.getRealname()+"郵件發送完畢");} catch (MessagingException e) {e.printStackTrace();}}}}}, new Date(),1000*30 );//1000ms*30=半分鐘//實際開發中,起始時間肯定是一個固定的時間//period:間隔時間 時間開發中,間隔時間是1天(為一天會有好多人過生日,把今天過生日的人給發送生日祝福)}@Overridepublic void contextDestroyed(ServletContextEvent sce) {// TODO Auto-generated method stub}}