import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; 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; // 配置發送郵件的環境屬性 final Properties props = new Properties(); /* * 可用的屬性: * mail.store.protocol / mail.transport.protocol / mail.host / * mail.user / mail.from */ // 表示SMTP發送郵件,須要進行身份驗證 props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.qq.com"); // 發件人的帳號 props.put("mail.user", "*******@qq.com"); // 訪問SMTP服務時須要提供的密碼 props.put("mail.password", "******"); // 構建受權信息,用於進行SMTP進行身份驗證 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 用戶名、密碼 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用環境屬性和受權信息,建立郵件會話 Session mailSession = Session.getInstance(props, authenticator); // 建立郵件消息 MimeMessage message = new MimeMessage(mailSession); // 設置發件人 InternetAddress form = new InternetAddress( props.getProperty("mail.user")); message.setFrom(form); // 設置收件人 InternetAddress to = new InternetAddress("******@qq.com"); message.setRecipient(RecipientType.TO, to); // 設置抄送 InternetAddress cc = new InternetAddress("******@qq.com"); message.setRecipient(RecipientType.CC, cc); // 設置密送,其餘的收件人不能看到密送的郵件地址 InternetAddress bcc = new InternetAddress("******@qq.com"); message.setRecipient(RecipientType.CC, bcc); // 設置郵件標題 message.setSubject("測試郵件"); // 設置郵件的內容體 message.setContent("<a href='http://www.baidu.com'>測試的HTML郵件</a>", "text/html;charset=UTF-8"); // 發送郵件 Transport.send(message); }