java 发送企业邮箱_Java调用api使用企业邮箱账户发送邮件
时间: 2024-02-02 14:02:55 浏览: 30
要发送企业邮箱,可以使用Java Mail API。以下是一个简单的示例代码,您可以使用它来发送邮件。
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
String to = "recipient@example.com"; // 收件人电子邮箱
String from = "sender@example.com"; // 发件人电子邮箱
String password = "yourpassword"; // 发件人邮箱密码
// 指定发送邮件的主机为 smtp.qq.com
String host = "smtp.qq.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置 From: 头部头字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部头字段
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:发件人的电子邮件地址
- password:发件人的电子邮件密码
- host:SMTP服务器主机名(例如,如果您使用Gmail,则为“smtp.gmail.com”)
此外,请确保在运行此代码之前,在您的计算机上安装了Java Mail API。