Невозможно отправить как текстовое сообщение, так и прикрепленный файл
Я не могу отправить сообщение после добавления файла документа.
После добавления msg.setFileName()
в коде msg.setText()
не работает.
Сообщение успешно доставлено с вложенным файлом, но текст сообщения не является телом сообщения. невозможно отправить как текстовое сообщение, так и прикрепленный файл.
ниже мой кодовый файл
public static void sendTo(String seniorId,String seniorName){
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "rptdby@gmail.com";//
final String password = "xxxxxxxxxxxxxxxx";
try{
Session session = Session.getDefaultInstance(props,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("rptdby@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(seniorId,false));
msg.setSubject("Suject");
msg.setText("Hi "+seniorName+"Sir"+"\n\nI am in India\nplease find my attached FILE.\n\nthanks\n\ndubey-theHarcourtian");
String filename = "C:\\Users\\arpit.dubey\\Desktop\\sysofnI\\Myfile.docx";
DataSource source = new FileDataSource(filename);
msg.setDataHandler(new DataHandler(source));
msg.setFileName("MyFile");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
}catch (MessagingException e){ System.out.println("Erreur d'envoi, cause: " + e);}
}
1 ответ
Решение
Вам нужно добавить файл в часть тела и добавить его в multipart. Мы не должны добавлять его в заголовок сообщения напрямую.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Testing Subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "/Mydocuments/kali/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent message successfully....");