javaqq邮箱发送附件
时间: 2025-01-06 20:50:04 浏览: 3
在Java中,可以通过JavaMail API来发送带附件的邮件。以下是一个简单的示例,展示了如何使用JavaMail API发送带附件的邮件:
1. 首先,需要在项目中引入JavaMail依赖。如果你使用的是Maven,可以在`pom.xml`中添加以下依赖:
```xml
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
```
2. 然后,编写代码来发送带附件的邮件:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
public class EmailWithAttachment {
public static void main(String[] args) {
// 邮件服务器的配置
String host = "smtp.example.com";
String from = "your_email@example.com";
String to = "recipient@example.com";
String subject = "Test Email with Attachment";
String bodyText = "This is a test email with an attachment.";
// 附件文件
String filePath = "path/to/your/file.txt";
// 设置邮件属性
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 创建会话
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@example.com", "your_password");
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
// 创建邮件正文和附件
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(bodyText);
MimeBodyPart attachmentPart = new MimeBodyPart();
File file = new File(filePath);
attachmentPart.attachFile(file);
// 组装邮件内容
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
```
这个示例展示了如何发送一封带附件的邮件。你可以根据需要修改邮件服务器的配置、发件人、收件人、主题、正文和附件路径。
阅读全文