使用Java发送电子邮件可以通过JavaMail API来实现。下面是一个基本的示例代码:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
// 配置SMTP服务器和认证信息
String host = "smtp.example.com";
String username = "your_username";
String password = "your_password";
// 创建Properties对象,设置邮件服务器和认证信息
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// 创建Session对象
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建MimeMessage对象
Message message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress("sender@example.com"));
// 设置收件人
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
// 设置邮件主题
message.setSubject("Hello JavaMail");
// 设置邮件内容
message.setText("This is a test email sent from Java.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
这段代码使用了JavaMail API来发送电子邮件。首先,需要配置SMTP服务器和认证信息,包括SMTP服务器地址、用户名和密码。然后,创建Properties对象并设置SMTP服务器和认证信息。接下来,创建Session对象,通过传递Properties对象和Authenticator对象来进行认证。然后,创建MimeMessage对象,并设置发件人、收件人、主题和内容。最后,调用Transport.send()方法发送邮件。
这是一个简单的示例,你可以根据实际需求进行扩展和定制。如果你想了解更多关于JavaMail API的详细信息,可以参考腾讯云的JavaMail API文档。
领取专属 10元无门槛券
手把手带您无忧上云