Java企业邮箱发送邮件
时间: 2023-07-29 12:07:22 浏览: 44
你可以使用JavaMail API来发送企业邮箱邮件。以下是一个示例代码:
```
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) throws Exception {
String to = "recipient@example.com";
String from = "sender@example.com";
String host = "smtp.example.com";
String username = "your_username";
String password = "your_password";
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
Session session = Session.getDefaultInstance(properties, authenticator);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Email body");
Transport.send(message);
System.out.println("Email sent successfully");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
```
你需要将以下变量替换为你实际使用的值:
- `to`: 收件人邮箱地址
- `from`: 发件人邮箱地址
- `host`: 发件人邮箱服务器主机名
- `username`: 发件人邮箱用户名
- `password`: 发件人邮箱密码
这个示例代码使用SMTP协议发送邮件。如果你需要使用其他协议或配置其他参数,可以根据JavaMail API的文档进行修改。