首页 > 解决方案 > java发送带有附件pdf的电子邮件不起作用

问题描述

我一直在寻找如何添加 pdf 并通过邮件发送很长时间.. 但是所有代码都失败了我终于尝试了这个,听起来对我来说是正确的,但它仍然显示错误这是我的文章:

   public static void send(String to, Document document) {
            String content = "dummy content"; //this will be the text of the email
            String subject = "dummy subject"; //this will be the subject of the email
            String receiver="aaa@yahoo.com";
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.localhost", "https://fr.yahoo.com/");
            properties.put("mail.smtp.auth", "true");
    
            Session session = Session.getDefaultInstance(properties,
                    new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    
            //2) compose message      
            ByteArrayOutputStream outputStream = null;
    
            try {
                //construct the text body part
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setText(content);
    
                //now write the PDF content to the output stream
                outputStream = new ByteArrayOutputStream();
                PdfWriter.getInstance(document, outputStream);
                byte[] bytes = outputStream.toByteArray();
    
                //construct the pdf body part
                DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
                MimeBodyPart pdfBodyPart = new MimeBodyPart();
                pdfBodyPart.setDataHandler(new DataHandler(dataSource));
                pdfBodyPart.setFileName("test.pdf");
    
                //construct the mime multi part
                MimeMultipart mimeMultipart = new MimeMultipart();
                mimeMultipart.addBodyPart(textBodyPart);
                mimeMultipart.addBodyPart(pdfBodyPart);
    
                //create the sender/recipient addresses
                InternetAddress iaSender = new InternetAddress(username);
                InternetAddress iaRecipient = new InternetAddress(receiver);
    
                //construct the mime message
                MimeMessage mimeMessage = new MimeMessage(session);
                mimeMessage.setSender(iaSender);
                mimeMessage.setSubject(subject);
                mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
                mimeMessage.setContent(mimeMultipart);
    
                //send off the email
                Transport.send(mimeMessage);
    
                System.out.println("sent from " + username
                        + ", to " + to
                        + "; server = " + ", port = ");
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                //clean off
                if (null != outputStream) {
                    try {
                        outputStream.close();
                        outputStream = null;
                    } catch (Exception ex) {
                    }
                }
            }
        }

起初它曾经向我显示关于主机的错误,但我纠正了它们,现在这就是错误显示

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect

任何人都可以更正我的代码吗

标签: javaemailpdfemail-attachments

解决方案


你让自己很难受!

看一下Simple Java Mail(开源,Jakarta Mail / JavaMail 周围的层),它带有一个应该很容易修改的gmail示例。对于您的情况,代码将是:

private void sendPdf(Document document) {
    // be sure to enable a one-time app password in Google, so 2-factor won't block you
    Mailer mailer = MailerBuilder.buildMailer("smtp.gmail.com", 25, username, password, TransportStrategy.SMTP);
    // or: MailerBuilder.buildMailer("smtp.gmail.com", 587, username, password, TransportStrategy.SMTP_TLS);
    // or: MailerBuilder.buildMailer("smtp.gmail.com", 465, username, password, TransportStrategy.SMTPS);

    Email email = EmailBuilder.startingBlank()
            .from(username)
            .to("aaa@yahoo.com")
            .withSubject("dummy subject")
            .withPlainText("dummy content")
            .withAttachment("test.pdf", producePdfData(document), "application/pdf");

    mailer.sendMail(email);
}

private byte[] producePdfData(Document document) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, outputStream);
    return outputStream.toByteArray();
}

现在您只需要填写正确的雅虎服务器和端口以及传输方法,但它应该可以工作。

如果您仍然无法建立连接,那么我猜您是在公司环境中尝试,并且您可能被代理(或者不太可能是防火墙)阻止。Simple Java Mail 支持代理连接(包括经过身份验证的代理),但如果它是防火墙,那么除非您设置 SSH 隧道或其他东西(可能不允许),否则您就不走运了。


推荐阅读