//pom.xml添加javax.mail的引用,或者項目引入javax.mail的jar包
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
發(fā)信示例代碼:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class Test {
public static void main(String[] args) {
// 設置發(fā)件人郵箱的屬性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-n.global-mail.cn"); // SMTP服務器地址 smtp-n.global-mail.cn 或者 smtp.global-mail.cn
props.put("mail.smtp.port", "25"); // SMTP服務器端口
// 啟用SSL
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
// 創(chuàng)建驗證信息
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test@example.cn", "******"); // 發(fā)送郵箱的賬號和密碼
}
};
// 創(chuàng)建會話
Session session = Session.getInstance(props, auth);
try {
// 創(chuàng)建郵件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("test@example.cn")); // 設置發(fā)件人郵箱
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@example.cn")); // 設置收件人郵箱
message.setSubject("Testing JavaMail"); // 設置郵件主題
message.setText("Hello, this is a test email sent using JavaMail."); // 設置郵件內容
// 發(fā)送郵件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}