我們可以使用第三方的郵箱服務器來發送郵件。
常用的郵件傳輸協議有2種:POP3/SMTP、IMAP/SMTP。
POP和IMAP的區別:在郵箱客戶端的操作,比如移動郵件、標記已讀,如果使用POP,是不會同步到郵箱服務器上的;如果使用IMAP,這些操作會同步到郵箱服務器上。
需要2個jar包
- javax.mail.jar
- activation.jar
示例 使用QQ郵箱服務器發送郵件
此處使用IMAP。可在 設置->賬戶 -> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 中配置。
@WebServlet("/sendMailServlet") public class SendMailServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties properties = new Properties(); properties.put("mail.transport.protocol", "smtp");// 連接協議 properties.put("mail.smtp.host", "smtp.qq.com");// 郵箱服務器主機名 properties.put("mail.smtp.port", 465);// 端口號 properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.ssl.enable", "true");//是否使用ssl安全連接 properties.put("mail.debug", "true");//是否在控制台顯示相關信息 //獲取會話對象 Session session = Session.getInstance(properties); //獲取郵件對象 Message message = new MimeMessage(session); try { // 設置發件人郵箱地址 message.setFrom(new InternetAddress("xxx@qq.com")); // 設置收件人郵箱地址 message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com")); //有多個收件人時,寫成數組形式 //InternetAddress[] receiverArr={new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")}; //message.setRecipients(Message.RecipientType.TO, receiverArr); // 設置郵件標題 message.setSubject("郵件標題"); // 設置郵件內容 message.setText("郵件內容"); //獲取郵差對象 Transport transport = session.getTransport(); //連接自己的郵箱賬戶,第二個參數是授權碼 transport.connect("xxx@qq.com", "xxxxxxxxxxx"); //發送郵件 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
使用時修改紅字部分即可。