java 发送邮件
时间: 2024-01-02 13:23:03 浏览: 103
以下是使用Java发送邮件的示例代码:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 配置SMTP服务器
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 创建会话对象
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@example.com", "your_password");
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Hello JavaMail");
message.setText("This is a test email from JavaMail.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
请注意,上述代码中的SMTP服务器地址、端口号、发件人邮箱、收件人邮箱、发件人邮箱密码等需要根据实际情况进行修改。
阅读全文