帮我写一个java 发送Exchange邮箱邮件demo
时间: 2024-01-14 17:05:08 浏览: 86
基于java的化妆品配方及工艺管理系统的开题报告.docx
好的,以下是一个简单的 Java 发送 Exchange 邮箱邮件的示例代码:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class ExchangeMailSender {
public static void main(String[] args) {
final String username = "your_username";
final String password = "your_password";
final String recipientEmail = "recipient_email_address";
final String subject = "Test Email";
final String body = "This is a test email sent from Java.";
Properties props = new Properties();
props.put("mail.smtp.host", "your_exchange_server");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587"); // Change to the appropriate port number
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
System.out.println("Failed to send email. Error message: " + e.getMessage());
}
}
}
```
请将代码中的以下信息替换为您自己的信息:
- `your_username`:您的 Exchange 邮箱用户名
- `your_password`:您的 Exchange 邮箱密码
- `recipient_email_address`:收件人的邮箱地址
- `your_exchange_server`:您的 Exchange 邮箱服务器域名或 IP 地址
请注意,此代码需要 JavaMail API 和 Exchange Web Services Java API。您需要将这些 API 添加到您的项目中才能运行此代码。
阅读全文