java实现foxmail发送邮件
时间: 2023-10-24 15:33:24 浏览: 40
要使用Java发送邮件,可以使用JavaMail API。以下是使用JavaMail API发送邮件的示例代码:
```java
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 SendEmail {
public static void main(String[] args) {
String to = "recipient@example.com"; // 收件人电子邮件地址
String from = "sender@example.com"; // 发件人电子邮件地址
String host = "smtp.example.com"; // SMTP服务器地址
// 设置系统属性
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
// 获取默认的Session对象
Session session = Session.getDefaultInstance(properties);
try {
// 创建一个默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置电子邮件的发件人、收件人、主题和正文
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("邮件主题");
message.setText("邮件正文");
// 发送电子邮件
Transport.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
```
在上面的示例代码中,需要将 `to`、`from` 和 `host` 替换为实际的值。同时,需要在项目中包含 JavaMail API 的 JAR 文件。