java发送邮件带附件
时间: 2023-09-01 11:13:37 浏览: 101
java 发送邮件(带附件)
5星 · 资源好评率100%
好的,以下是Java发送带附件的邮件的示例代码:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// 收件人邮箱地址
String to = "recipient@example.com";
// 发件人邮箱地址
String from = "sender@example.com";
// 发件人邮箱密码或授权码
String password = "your_password_or_auth_code";
// 邮件主题和正文
String subject = "Test email with attachment";
String body = "Please see the attached file.";
// 创建邮件会话
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(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.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// 创建邮件正文
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(body);
// 创建邮件附件
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile("path/to/attachment");
// 将正文和附件添加到邮件消息中
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (Exception e) {
System.err.println("Failed to send email: " + e.getMessage());
}
}
}
```
在上面的代码中,需要将以下信息替换为实际的值:
- `to`:收件人邮箱地址
- `from`:发件人邮箱地址
- `password`:发件人邮箱密码或授权码
- `subject`:邮件主题
- `body`:邮件正文
- `props.put("mail.smtp.host", "smtp.example.com")`:SMTP服务器地址
另外,需要将附件的文件路径替换为实际的路径。
阅读全文