用java代码编程实现邮件发送功能。
时间: 2023-12-10 15:39:16 浏览: 35
你可以使用JavaMail API来实现邮件发送功能。以下是一个简单的代码示例:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailSender {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_email_password";
String recipient = "recipient_email@example.com";
String subject = "Test Email";
String body = "This is a test email sent using JavaMail API.";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.example.com"); // Replace with your SMTP server address
props.put("mail.smtp.port", "587"); // Replace with your SMTP server port number
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在上面的代码中,你需要将 `username` 和 `password` 替换为你的发件人邮箱地址和密码。你还需要将 `recipient` 替换为收件人邮箱地址,`subject` 替换为邮件主题,`body` 替换为邮件正文。同时,你还需要将 `props.put("mail.smtp.host", "smtp.example.com");` 替换为你的 SMTP 服务器地址。
如果你已经配置好了 JavaMail API 的环境,那么你可以直接运行上面的代码来发送邮件。