我想用java發送附件中的文件。 我有兩個類,其中一個指定文件位置,第二個類用作工具類發送電子郵件 因此,當我執行第一個類時,它不會發送電子郵件。Java用附件中的文件發送電子郵件
第一類:
public class SendFile {
private static String[] args;
public static void sendEmail(File filetosend) throws IOException, Exception{
//public static void main(String[] args) throws IOException {
final String username = "[email protected]";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Attach file Test from Netbeans");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
//String filetosend = ("c:\\file.txt");
DataSource source = new FileDataSource(filetosend);
System.out.println("The filetosend is ="+filetosend);
messageBodyPart.setDataHandler(new DataHandler(source));
System.out.println("The source is ="+source);
messageBodyPart.attachFile(filetosend);
System.out.println("The file name is ="+messageBodyPart.getFileName());
multipart.addBodyPart(messageBodyPart);
System.out.println("The message body part is ="+messageBodyPart);
message.setContent(multipart);
System.out.println("The message multi part is ="+multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("The message is ="+message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
而第二類:
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws Exception {
}
File file;
public void Test() throws IOException, Exception{
System.out.println("Sending the file...");
File filetosend = new File("c:\\file.txt");
SendFile.sendEmail(filetosend);
}
}
沒有錯誤,但沒有發送的文件。 請任何幫助,謝謝
我發現了一個類似的問題http://stackoverflow.com/questions/16117365/sending-mail-attachment-using-java – Jaydee 2014-09-03 14:48:06
的問題不是要發送的文件。我想從另一個班級獲得檔案。 – 2014-09-03 15:27:19