如何发送附件在发送时具有扩展名的电子邮件

时间:2014-05-23 10:55:31

标签: java email attachment

我正在尝试发送附件附件的电子邮件。整个过程工作正常,除了附件发送的部分发送没有扩展名的附件。

例如,发送File.rar即会收到file

我正是这样做的:

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);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

使用评论中的建议,正确的方法是setDisposition,你可以为有问题的MimeBodyPart设置它。因此,使用上面的代码,可以做到:

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