Android使用qq邮箱发送附件代码
时间: 2024-02-03 13:14:21 浏览: 62
下面是使用QQ邮箱发送附件的Android代码示例:
```java
public class MailSender {
private static final String MAIL_HOST = "smtp.qq.com";
private static final String SMTP_PORT = "465"; // SSL协议的端口号
private static final String FROM_ADDRESS = "your_qq_mail@qq.com";
private static final String PASSWORD = "your_qq_mail_password";
private static final String TO_ADDRESS = "recipient_address@example.com"; // 收件人邮箱
public static void send(String subject, String content, String filePath) {
Properties properties = new Properties();
properties.put("mail.smtp.host", MAIL_HOST);
properties.put("mail.smtp.port", SMTP_PORT);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_ADDRESS));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
message.setSubject(subject);
// 创建邮件正文
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(content, "text/html;charset=UTF-8");
// 创建邮件附件
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(filePath);
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
// 将正文和附件合并到一个Multipart对象中
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
// 将Multipart对象添加到邮件中
message.setContent(multipart);
// 发送邮件
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
使用时,只需要调用`MailSender.send()`方法,并传入邮件主题、邮件正文和附件文件路径即可。注意修改代码中的`FROM_ADDRESS`、`PASSWORD`和`TO_ADDRESS`为你自己的邮箱地址和密码。
阅读全文