要实现Java发送邮件,可以使用JavaMail API。以下是一个简单的示例代码,演示了如何使用JavaMail API发送邮件:
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) { // 发件人邮箱地址 String from = "your-email@example.com"; // 发件人邮箱密码或授权码 String password = "your-password"; // 收件人邮箱地址 String to = "recipient-email@example.com"; // 设置邮件属性 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"); // 创建会话 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建邮件对象 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."); // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { e.printStackTrace(); } } }
在上面的示例代码中,请确保将以下变量替换为实际的值:
-
from
:发件人的邮箱地址 -
password
:发件人的邮箱密码或授权码 -
to
:收件人的邮箱地址 -
mail.smtp.host
:SMTP服务器主机地址 -
mail.smtp.port
:SMTP服务器端口号
运行上述代码,将会使用JavaMail API发送一封包含文本内容的测试邮件。如果一切正常,你将在控制台上看到"Email sent successfully."的输出。