写一个发送邮件的Java代码
时间: 2023-05-27 22:03:24 浏览: 60
这里提供一个基本的发送邮件的Java代码:
```
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 发送邮件的信息
String host = "smtp.gmail.com";
String user = "你的邮箱地址";
String password = "你的邮箱密码";
String to = "接收邮件的邮箱地址";
// 创建邮件会话
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
try {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("测试邮件");
message.setText("这是一封测试邮件,请勿回复。");
// 发送邮件
Transport.send(message);
System.out.println("邮件已发送。");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
```
注:这个代码需要添加Java Mail API和Java Activation Framework两个库才能编译运行。同时,SMTP服务器的地址和端口号需要根据不同邮箱进行修改。