用java写一个发送邮件的代码
以下是使用JavaMail库发送邮件的示例代码:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender {
public static void main(String[] args) {
String host = "smtp.example.com"; // 邮件服务器地址
String port = "587"; // 端口号
String username = "your_email@example.com"; // 发件人邮箱账号
String password = "your_email_password"; // 发件人邮箱密码
String recipient = "recipient@example.com"; // 收件人邮箱地址
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", port);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject("Test Email");
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. Error message: " + e.getMessage());
}
}
}
请注意,您需要使用您自己的邮件服务器地址、端口号、发件人邮箱账号和密码,以及收件人邮箱地址。此外,您需要在运行代码之前确保已经下载并导入了JavaMail库。
原文地址: https://www.cveoy.top/t/topic/Ys9 著作权归作者所有。请勿转载和采集!