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.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtils {
/**
11 * 發送郵件
12 * @param to 給誰發
13 * @param text 發送內容
14 */
public static void send_mail(String to,String text) throws MessagingException {
//創建連接對象 連接到郵件服務器
Properties properties = new Properties();
//設置發送郵件的基本參數
//發送郵件服務器 根據發送郵箱的服務器編寫
properties.put(“mail.smtp.host”, “smtp.163.com”);
//發送端口
properties.put(“mail.smtp.port”, “25”);
properties.put(“mail.smtp.auth”, “true”);
//設置發送郵件的賬號和密碼
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//兩個參數分別是發送郵件的賬戶和密碼
return new PasswordAuthentication(“發件人的郵箱”,”發件人的郵箱密碼”);
}
});
//創建郵件對象
Message message = new MimeMessage(session);
//設置發件人
message.setFrom(new InternetAddress(“發件人的郵箱”));
//設置收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
//設置主題
message.setSubject(“發送主題”);
//設置郵件正文 第二個參數是郵件發送的類型
message.setContent(text,”text/html;charset=UTF-8″);
//發送一封郵件
Transport.send(message);
}
}
驗證碼工具類
public class RandomUtils {
public String getRandom() {
String[] beforeShuffle = new String[] { “1”, “2”, “3”, “4”, “5”, “6”,
“7”, “8”, “9”, “0”};
List list = Arrays.asList(beforeShuffle);
Collections.shuffle(list);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i ) {
sb.append(list.get(i));
}
String afterShuffle = sb.toString();
String result = afterShuffle.substring(5, 9);
System.out .print(result) ;
return result;
}
}
測試:
發件人的郵箱
import java.util.Random;
import javax.mail.MessagingException;
import com.cblue.email.utils.EmailUtils;
import com.cblue.email.utils.RandomUtils;
/**
* 測試
* @author lenovo
*
*/
public class EmailTest {
public static void main(String[] args) {
//創建的隨機數的工具類,生成驗證碼
RandomUtils randomUtils = new RandomUtils();
String random = randomUtils.getRandom();
try {
EmailUtils.send_mail(“收件人郵箱”, “用戶您好您的驗證碼為:” random);
System.out.println(“郵件發送成功!”);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
如果,你對上面的內容還有疑問,推薦選擇三五互聯企業云郵箱!有專人協助您解答郵箱疑問。
三五互聯企業云郵箱,采用分布式集群架構,數據多份寫入,規避單點故障,全球智能中繼,更安全穩定。企業郵箱無限空間,極速收發,支持層級子文件夾,郵件撤回,日程微信通知、郵件監管、自定義工作報告功能、郵件歸檔、SSL部署等幾十項功能。而且價格實惠,還可以免費試用!
企業郵箱免費試用入口:http://www.shinetop.cn/services/mail/