文件未附加到电子邮件

时间:2014-07-24 09:15:31

标签: java javamail

我有以下问题,我正在尝试将文件附加到正在发送的邮件中,但它不会附加到邮件中。

请参阅以下代码了解邮件:

public static boolean sendEmail(String subject, String emailMessage, String from, String to[],String[] attachFiles ) throws MessagingException, IOException {

    boolean result = true;
    try {
        final String username = "nmtsystem@gmail.com";
        final String password = "nMT@DMIn!";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {

                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];
        // To get the array of addresses
        for (int i = 0; i < to.length; i++) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }

        for (int i = 0; i < toAddress.length; i++) { // changed from a while loop
            message.addRecipient(javax.mail.Message.RecipientType.TO, toAddress[i]);
        }

//创建消息部分         MimeBodyPart messageBodyPart = new MimeBodyPart();

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();

            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            multipart.addBodyPart(attachPart);
        }
    }
        message.setSubject(subject);
        message.setContent("<p><font size=\"-1\" face=\"Verdana, Arial, Helvetica, sans-serif\">" + emailMessage + "</font></p>", "text/html");

        Transport.send(message);

    } catch (MessagingException ex) {
        result = false;
        throw ex;
    }
    return result;
}

这是邮件正文的代码:

        public void queryMailPayAt() {
    String sql = "select caseNumber from tblpay@qlheader where transactionid = " + selectedQuery.getRecId();
    String caseId = "";

    try {
        Connection con = DatabaseHandler.getDBConnection(DatabaseTypes.TRANSACTION_DATABASE);
        ResultSet result = DatabaseHandler.executeQuery(con, sql);
        while (result.next()) {
            caseId = result.getString("caseNumber");
        }
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An error occurred.", e.getMessage()));
        String ex = e.getMessage();
        String ex1 = e.getLocalizedMessage();
        System.out.println(ex + " " + ex1);
    }

    String from = "admin@nmtservice.co.za";
    String style = "<font size=\"-1\" face=\"Verdana, Arial, Helvetica, sans-serif\">";
    String msgPrefix = "<h4>New B.I.N has been logged</h4>";
    String msg = "<p>See details for newly logged B.I.N.</p>"
            + "<p>Issue Case ID: " + caseId + "</p>"
            + "<table><tbody>"
            + "<tr><td>" + style + "Username: </font></td><td>" + style + user.getUsername() + "</font></td></tr>"
            + "<tr><td>" + style + "First Name: </font></td><td>" + style + user.getFirstName() + "</font></td></tr>"
            + "<tr><td>" + style + "Last Name: </font></td><td>" + style + user.getLastName() + "</font></td></tr>"
            + "<tr><td>" + style + "Transaction ID: </font></td><td>" + style + selectedQuery.getRecId() + "</font></td></tr>"
            + "</tbody></table>"
            + "<p> If this is a valid query please confirm on the Open queries page </p>"
            + "<p>Please contact <a href=\"mailto:support@payat-it.co.za\">Pay@ Support</a> for any further assistance.</p>";

    String emailMessage = msgPrefix + msg;
    String subject = "New Logged B.I.N: " + caseId;
    String[] attachFiles = new String[1];
    attachFiles[0] = "C:\\Users\\kroon_000\\Desktop\\files\\"+ caseId + ".pdf" ;
    try {
        String[] to = {"dirk@nmt-it.co.za",  user.getEmailAddress() };
        Utils.sendEmail(subject, emailMessage, from, to, attachFiles);
    } catch (Exception ex) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An error occurred.", "Please try again."));
    }
}

如果有人能帮助我,我做错了什么,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

在您的代码中,multipart已创建但未使用。你应该添加:

message.setContent(multipart);