java發送郵件

來源:互聯網
上載者:User

標籤:對象   實作類別   put   ges   user   內容   系統檔案   sse   tac   

前提:匯入發Java郵件的jar包:
activation.jar additionnal.jar(第三方用戶端,沒有時會) mail.jar
additionnal.jar(第三方用戶端,沒有時會出現在什麼路徑下,系統檔案找不到)
步驟一:編寫發郵件類
package com.gl.util;


import java.util.Properties

import javax.mail.*;
import javax.mail.internet.*;


public class MailUtil {
//傳入發郵件的地址和郵件啟用碼
public static void sendMail(String to,String code){
//發送郵件的伺服器
String host = "smtp.qq.com";
//使用者名稱
String username="[email protected]";
//第三方用戶端驗證密碼,需要在QQ郵箱的賬戶/SMTP/POP3/IMAP下開啟/SMTP/POP3
//發簡訊得到第三方用戶端登入驗證密碼
String password="************";
//Session對象
Properties props = new Properties();
props.put("mail.smtp.host", host);
//發送郵件的連接埠號碼
props.put("mail.smtp.port", "465");
/* props.put("mail.transport.protocol", "smtp");*/
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable","true");///使用 STARTTLS安全連線
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);

//Message對象
MimeMessage message = new MimeMessage(session);
// 設定寄件者
try {
message.setFrom(new InternetAddress(username));
//設定收件者
message.setRecipients(Message.RecipientType.TO,to);
//設定主題
message.setSubject("來自於xionger商城的帳號啟用郵件");

//設定內容
message.setContent("<h1>來自於熊二商城的帳號啟用郵件!啟用請點擊以下連結</h1><br><h3><a href=‘http://localhost:8888/shop/usersActive.action?Users.u_code="+code+"‘>http://localhost:8888/shop/register.action?code="+code+"</a></h3>","text/html;charset=UTF-8");

message.saveChanges(); // implicit with send()

Transport transport = session.getTransport("smtp");

transport.connect(host, username, password);

transport.sendMessage(message, message.getAllRecipients());

transport.close();



} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
第二步:實作類別,調用發郵件的方法(註冊等等),此例是struts
public String Reg(){
UsersServiceImpl usersServiceImpl=(UsersServiceImpl) ac.getBean("usersService");
users.setU_state(false);
String u_code = UUID.randomUUID().toString().replace("-","");
System.out.println(u_code);
System.out.println(users.getU_email());
users.setU_code(u_code);
usersServiceImpl.save(users);
MailUtil.sendMail(users.getU_email(),u_code);
return "regOK";
}

 

java發送郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.