В Javamail Attachment не отображается - PullRequest
0 голосов
/ 21 января 2020

В приложении Javamail вложение не отображается

Я пытался отправить письмо с вложением Оно отправлено и получено Но в полученном письме вложение не отображается не отображается вложение пусто и вот код:

@Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtp");
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("*******@gmail.com");
javaMailSender.setPassword("*********");
Properties props = ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.mime.multipart.allowempty", "true");
javaMailSender.setJavaMailProperties(props);
return javaMailSender;
}
{
message.setSubject(mailServiceDTO.getSubject());
message.setText(mailServiceDTO.getSubject(), "text/html");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailServiceDTO.getSubject(), "text/html");
for (EmailAttachment attachment : mailServiceDTO.getAttachments()) {
message.addAttachment(attachment.getAttachmentName(), new ByteArrayResource(attachment.getAttachmentContent().getBytes()));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(messageBodyPart);
mimeMessage.setContent(mp);
javaMailSender.send(mimeMessage);
}

Ответы [ 2 ]

0 голосов
/ 21 января 2020

Добавить несколько вложений ..

public static void main(String[] args) {

		final String fromEmail = ""; // requires valid gmail id
		final String password = "";// correct password for gmail id
		final String toEmail = ""; // can be any 
		System.out.println("TLSEmail Start");
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com"); // SMTP Host
		props.put("mail.smtp.port", "587"); // TLS Port
		props.put("mail.smtp.auth", "true"); // enable authentication
		props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS

		Authenticator auth = new Authenticator() {
			// override the getPasswordAuthentication method
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(fromEmail, password);
			}
		};

		Session session = Session.getDefaultInstance(props, auth);
		System.out.println("Session created");
		

		sendAttachmentEmail(session,fromEmail, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");

	

	}


public static void sendAttachmentEmail(Session session,String fromEmail, String toEmail, String subject, String body){
	try{
         MimeMessage msg = new MimeMessage(session);
         msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
	     msg.addHeader("format", "flowed");
	     msg.addHeader("Content-Transfer-Encoding", "8bit");
	      
	     msg.setFrom(new InternetAddress(fromEmail));

	     msg.setReplyTo(InternetAddress.parse(toEmail, false));

	     msg.setSubject(subject, "UTF-8");

	     msg.setSentDate(new Date());

	     msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
	      
         // Create the message body part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText(body);
         
         // Create a multipart message for attachment
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         
         String filename1 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.zip";
         addAttachment(multipart, filename1);
         String filename2 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.log";
         addAttachment(multipart, filename2);

         // Send the complete message parts
         msg.setContent(multipart);

         // Send message
         Transport.send(msg);
         System.out.println("EMail Sent Successfully with attachment!!");
      }catch (MessagingException e) {
         e.printStackTrace();
      }
}

private static void addAttachment(Multipart multipart, String filename) throws MessagingException
{
    DataSource source = new FileDataSource(filename);
    BodyPart messageBodyPart = new MimeBodyPart();        
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
}
0 голосов
/ 21 января 2020

вы можете использовать MimeMessageHelper в весенней почте.

Пример

        MimeMessage msg = javaMailSender.createMimeMessage();

    MimeMessageHelper mailMessage = null;
    List<PathSource> pathSourceList = request.getMailAttachList();
    if (pathSourceList != null && pathSourceList.size() > 0)
        mailMessage = new MimeMessageHelper(msg, true);
    else
        mailMessage = new MimeMessageHelper(msg, false);
    // .... 
    if (pathSourceList != null && pathSourceList.size() > 0) {
        for (PathSource filepath : pathSourceList) {
            ByteArrayResource stream = new ByteArrayResource(DatatypeConverter.parseBase64Binary(
                    filepath.getData()));
            mailMessage.addAttachment(filepath.getFileName(), stream);
        }
    }
    try {
        javaMailSender.send(mailMessage.getMimeMessage());
    } catch (Exception ex) {
        log.error("server info {}", serverModel.toString());
        throw ex;
    }
...