简体   繁体   中英

How to send an email whose attachment has an extension on delivery

I'm trying to send an email with an attachment. The whole thing works fine, except for the part that the attachment sent sends the attached file with no extension.

For example, sending File.rar will receive file

This is how I'm doing it:

public class EmailSender {

    public static void main(String[] args) {
        String TO = "Receiver@yahoo.com";
        String host = "smtp.gmail.com";
        String port = "465";
        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties mailConfig = new Properties();
        mailConfig.put("mail.smtp.host", host);
        mailConfig.put("mail.smtp.socketFactory.port", port);
        mailConfig.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        mailConfig.put("mail.smtp.auth", "true");
        mailConfig.put("mail.smtp.port", port);

        Session session = Session.getDefaultInstance(mailConfig,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("Username", "Password");
                }
            });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
            message.setSubject("Email with Attachment SUBJECT");

            BodyPart messageBodyTxt = new MimeBodyPart();
            messageBodyTxt.setText("Email with Attachment BODY");

            MimeBodyPart messageBodyAttachment = new MimeBodyPart();
            String filePath = "D:\\Unlocker1.9.2.rar";
            DataSource source = new FileDataSource(filePath);
            messageBodyAttachment.setDataHandler(new DataHandler(source));
            messageBodyAttachment.setFileName("Unlocker1.9.2" + ".rar");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyTxt);
            multipart.addBodyPart(messageBodyAttachment);
            message.setContent(multipart);

            Transport.send(message);
            System.out.println("Email sent successfully");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }
}

Using the advice from the comment, the proper method would be setDisposition and you would set it for the MimeBodyPart in question. Therefore, with the code above, one would do:

messageBodyAttachment.setDisposition(javax.mail.Part.ATTACHMENT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM