Java 发送邮件功能
时间: 2023-11-03 20:04:40 浏览: 38
Java 发送邮件可以使用 JavaMail API 实现。下面是一个简单的发送邮件的示例代码:
```java
import java.util.Properties;
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) {
final String username = "your_email_address";
final String password = "your_email_password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
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("your_email_address"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient_email_address"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
其中,需要将 `your_email_address` 和 `your_email_password` 替换为你自己的邮箱地址和密码,`recipient_email_address` 替换为接收邮件的地址。
上述代码使用了 Gmail SMTP 服务器,如果你使用其他邮箱,需要将 `props.put("mail.smtp.host", "smtp.gmail.com");` 替换为你所使用的邮箱的 SMTP 服务器地址和端口号。