如何使用javax.mail.jar为附加到电子邮件的图像添加文件名

问题描述 投票:0回答:1

我能够成功地向自己发送带有图像的电子邮件,但是,该图像是一个名为noname的文件(无论如何都在gmail上)。如何更改附加到电子邮件中的图像的文件名?

以下是我用于发送带有图片的电子邮件的代码部分:

    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);
        }
    }
java email
1个回答
1
投票

看看javax.mail.internet.MimeBodyPart.setFileName(String)

您可以在创建零件后执行此操作:

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

请参阅java docs here

© www.soinside.com 2019 - 2024. All rights reserved.