http://download.csdn.net/detail/viviwen123/3677063是之前上傳的資源,但隻能發送普通郵件,不能發送附件。現在CSDN不知怎麼了,竟然不可以修改說明,隻好在此發文更正了。隻要在GMailSender.java檔案裡加入以下函數:
public void send_mail_file(String str_title, String str_body,
String str_from_mail, String str_to_mail, String str_file_path) {
MimeMessage message = new MimeMessage(session); // Define message
DataHandler handler = new DataHandler(new ByteArrayDataSource(
str_body.getBytes(), "text/plain"));
try {
message.setFrom(new InternetAddress(str_from_mail)); // Set the from address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
str_to_mail));// Set the to address
message.setSubject(str_title);// Set the subject
//message.setText(str_body);// Set the content
message.setDataHandler(handler);
} catch (Exception e) {
}
MimeBodyPart attachPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(str_file_path); // 打開要發送的檔案
try {
attachPart.setDataHandler(new DataHandler(fds));
attachPart.setFileName(fds.getName());
} catch (MessagingException e) {
e.printStackTrace();
}
MimeMultipart allMultipart = new MimeMultipart("mixed"); // 附件
try {
allMultipart.addBodyPart(attachPart);// 添加
message.setContent(allMultipart);
message.saveChanges();
Transport.send(message);// 開始發送
} catch (MessagingException e) {
e.printStackTrace();
}
}
調用此函數即可實作發送附件。親測可用。