2017-12-24 6 views
0

イメージをメールで送信することはできますが、画像はnonameという名前のファイルになります。電子メールに添付している画像のファイル名を変更するにはどうすればよいですか? javax.mail.internet.MimeBodyPart.setFileName(String)javax.mail.jarを使用して電子メールに添付された画像にファイル名を追加するには

public void SendEmail(
      String smtp_host_, 
      String smtp_port_, 
      String smtp_username_, 
      String smtp_password_, 
      String to_, 
      String subject_, 
      String body_, 
      String image_path_) { 
     Properties props = new Properties(); 
     props.put("mail.smtp.starttls.enable", "true"); 
     props.put("mail.smtp.auth", "true"); 
     props.put("mail.smtp.host", smtp_host_); 
     props.put("mail.smtp.port", smtp_port_); 

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

     try { 

      Message message = new MimeMessage(session); 

      message.setSubject(subject_); 
      message.setFrom(new InternetAddress(smtp_username_)); 
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to_)); 

      MimeMultipart multipart = new MimeMultipart("related"); 

      BodyPart messageBodyPart = new MimeBodyPart(); 
      messageBodyPart.setContent(body_, "text/html"); 
      multipart.addBodyPart(messageBodyPart); 

      messageBodyPart = new MimeBodyPart(); 
      DataSource fds = new FileDataSource(image_path_); 
      messageBodyPart.setDataHandler(new DataHandler(fds)); 
      messageBodyPart.setHeader("Content-ID","<image>"); 
      multipart.addBodyPart(messageBodyPart); 

      message.setContent(multipart); 

      Transport transport = session.getTransport(); 
      transport.connect(); 
      transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); 
      transport.close(); 
     } 
     catch (MessagingException e) { 
      throw new RuntimeException(e); 
     } 
    } 
+1

FileDataSourceとsetDataHandlerの略記は、[attachFile](https://docs.oracle.comさ呼び出します/javaee/7/api/javax/mail/internet/MimeBodyPart.html#attachFile-java.io.File-)メソッドを使用する必要があります。このメソッドは、本体部分の名前も設定する必要があります。 – VGR

答えて

1

ルック:ここ

は、私がイメージして電子メールを送信するために使用していたコードのセクションです。

あなたはパートを作成した後にそれを行うことができます。

messageBodyPart = new MimeBodyPart(); 
((MimeBodyPart) messageBodyPart).setFileName("filename.ext"); 

参照のJavaドキュメントhere

関連する問題