java如何实现发送带存储在服务器的附件的邮件
时间: 2024-03-02 16:54:38 浏览: 20
要在Java中发送带附件的邮件,可以使用JavaMail API。以下是一个示例代码,可以实现将附件添加到邮件中并发送邮件:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// 邮件信息
String host = "smtp.example.com";
String from = "your-email@example.com";
String password = "your-email-password";
String to = "recipient@example.com";
String subject = "Email with Attachment";
String body = "Please see the attached file.";
// 附件信息
String filename = "file.txt";
String filepath = "/path/to/file.txt";
// 设置邮件属性
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
// 创建Session
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
// 创建邮件内容
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
// 创建附件
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// 设置邮件内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("Email with Attachment sent successfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
需要注意的是,这个示例代码中的邮件服务器地址、发件人邮箱、发件人邮箱密码、收件人邮箱、附件文件名和附件文件路径需要根据实际情况进行修改。