Ненужное вложение добавлено в почту при запуске почты с помощью java mail api - PullRequest
2 голосов
/ 28 марта 2019

Я отправляю электронное письмо со встроенным изображением и html-файлом в качестве вложения, используя почтовый ява, но сегодня я заметил, что в письме «ATT00001.bin» было отправлено ненужное вложение, которое я нигде не добавил в коде,

На самом деле это было настолько шокирующим для меня, что я попробовал свой уровень, изменив имя вложения, но не смог найти решение (до последнего дня оно работало нормально (я имею в виду, что я получал одно встроенное изображение и одно вложение в почте).)

[![// Recipient's email ID needs to be mentioned.
      String to = "mail@example.com";

      // Sender's email ID needs to be mentioned
      String from = "sender@example.com";

      final String username = "user";//change accordingly
      final String password = "pwd";//change accordingly


      // Assuming you are sending email through outlook mail
      String host = "outlook.office365.com";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");


      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
            }
         });

      try {

         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));

         // Set Subject: header field
         //message.setSubject("Testing Subject");


         // This mail has 2 part, the BODY and the embedded image
         MimeMultipart multipart = new MimeMultipart("related");

         // first part (the html)
         BodyPart messageBodyPart = new MimeBodyPart();
         String htmlText = "<p>Hi Team,</p> <p>Please find the Report for the day   </p> <p>&nbsp;</p> <img src=\"cid:image\">  <p>&nbsp;Regards,</p> <p>&nbsp;Team</p>";
         messageBodyPart.setContent(htmlText, "text/html");
         // add it
         multipart.addBodyPart(messageBodyPart);

         // second part (the image)
         messageBodyPart = new MimeBodyPart();
         //local file path
         DataSource fds = new FileDataSource("$localDirectory");

         messageBodyPart.setDataHandler(new DataHandler(fds));
         messageBodyPart.setHeader("Content-ID", "<image>");

         // add image to the multipart
         multipart.addBodyPart(messageBodyPart);




         //adding attachment as well
 // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "$reportFileName";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName("API_SummaryReport_${fileNamePart}+.html");
         multipart.addBodyPart(messageBodyPart);


        // put everything together
         message.setContent(multipart);
         // Send message
         Transport.send(message);

         log.info("Email sent successfully....");

      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }][1]][1]

ожидание только одного вложения, но получение дополнительного файла в формате bin, пожалуйста, найдите изображение для справки

1 Ответ

1 голос
/ 28 марта 2019

Пожалуйста, измените код на это:

String to = "mail@example.com";

  // Sender's email ID needs to be mentioned
  String from = "sender@example.com";

  final String username = "user";
  final String password = "pwd";

  String host = "outlook.office365.com";

  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", "587");


  Session session = Session.getInstance(props,
     new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
           return new PasswordAuthentication(username, password);
        }
     });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

       // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(msgSubject);
        message.setSentDate(new java.util.Date());
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        String htmlText = "<p>Hi Team,</p> <p>Please find the Report for the day   </p> <p>&nbsp;</p> <img src=\"cid:image\">  <p>&nbsp;Regards,  </p> <p>&nbsp;Team</p>";
       messageBodyPart.setContent(htmlText, "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.setHeader("Content-ID", "<image>");
        //add this to avoid unwanted attachment.
        imagePart.setDisposition(MimeBodyPart.INLINE);
        imagePart.attachFile(new File("C:\\abc.png"));
        multipart.addBodyPart(imagePart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | IOException ex) {
         throw new RuntimeException(e);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...