以下是一个使用Java发送邮件的代码示例:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
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;
public class SendEmail {
public static void main(String[] args) {
// 设置邮件服务器主机名
String host = "smtp.example.com";
// 设置发送者邮箱
String from = "sender@example.com";
// 设置接收者邮箱
String to = "receiver@example.com";
// 设置发送者邮箱用户名
final String username = "sender_username";
// 设置发送者邮箱密码
final String password = "sender_password";
// 创建Properties对象,用于设定邮件相关信息
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
// 创建会话对象,通过输入用户名和密码进行身份验证
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息对象
Message message = new MimeMessage(session);
// 设置发送者邮箱地址
message.setFrom(new InternetAddress(from));
// 设置接收者邮箱地址
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// 设置邮件主题
message.setSubject("Hello World!");
// 设置邮件内容
message.setText("This is a test email sent from Java.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
System.out.println("Failed to send email.");
e.printStackTrace();
}
}
}
请确保将 host
、from
、to
、username
以及 password
替换为正确的邮箱服务器和邮箱账号信息。