要實(shí)現(xiàn)Java發(fā)送郵件,可以使用JavaMail API。以下是一個(gè)簡(jiǎn)單的示例代碼,演示了如何使用JavaMail API發(fā)送郵件:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) {
// 發(fā)件人郵箱地址
String from = "your-email@example.com";
// 發(fā)件人郵箱密碼或授權(quán)碼
String password = "your-password";
// 收件人郵箱地址
String to = "recipient-email@example.com";
// 設(shè)置郵件屬性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 創(chuàng)建會(huì)話
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 創(chuàng)建郵件對(duì)象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("JavaMail API Test");
message.setText("Hello, This is a test email from JavaMail API.");
// 發(fā)送郵件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
在上面的示例代碼中,請(qǐng)確保將以下變量替換為實(shí)際的值:
from
:發(fā)件人的郵箱地址
password
:發(fā)件人的郵箱密碼或授權(quán)碼
to
:收件人的郵箱地址
mail.smtp.host
:SMTP服務(wù)器主機(jī)地址
mail.smtp.port
:SMTP服務(wù)器端口號(hào)
運(yùn)行上述代碼,將會(huì)使用JavaMail API發(fā)送一封包含文本內(nèi)容的測(cè)試郵件。如果一切正常,你將在控制臺(tái)上看到"Email sent successfully."的輸出。