通过java mail api发送带附件的邮件

时间:2015-05-17 05:22:02

标签: java javamail

我创建了以下程序,因为它用于通过java邮件api发送邮件,它现在正常工作我必须修改它,因为我还想附加一个存储在我的c:中的pdf文件,请建议我如何修改下面这个程序,这样当它发送邮件时,它也应该发送存储在我的c:驱动器中的abc.pdf文件作为附件

C:\ abc.pdf

下面是我已开发仪式的程序,现在它没有发送任何附件

  public class BrokMailTest {

        public static void main(String[] args) {

            String mailSmtpHost = "16.66.66.66";
            String mailSmtpPort = "2345" ;

             String mailTo = "avdg@abc.com";
            //String mailCc = "avdg@abc.com ";
            String mailFrom = "avdg@abc.com";
            String mailSubject = "fghfdwwrtuijjjjuj";
            String mailText = "wertyuuiiojgfdss";
            sendEmail(mailTo,  mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
        }

        public static void sendEmail(String to,  String from, String subject, String text, String smtpHost , String mailSmtpPort) {
            try {
                Properties properties = new Properties();
                properties.put("mail.smtp.host", smtpHost);
                properties.put("mailSmtpPort", mailSmtpPort);
                //obtaining the session
                Session emailSession = Session.getDefaultInstance(properties);
                Message emailMessage = new MimeMessage(emailSession);
                emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                //emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse("avdg@abc.com,aswq@gmail.com"));
                Address[] cc = new Address[] {
                 new InternetAddress("avdg@abc.com"),
                 new InternetAddress("asd@gmail.com")};
                 emailMessage.addRecipients(Message.RecipientType.CC, cc);
                emailMessage.setFrom(new InternetAddress(from));
                emailMessage.setSubject(subject);
                emailMessage.setContent(emailMessage, "text/html");
                emailMessage.setText(text);
                emailSession.setDebug(true);
                Transport.send(emailMessage);
            }    catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }

    }

1 个答案:

答案 0 :(得分:0)

您需要创建一个多部分。多部分将具有消息部分和附件部分。 JavaMail 1.4的示例:

    MimeBodyPart messageBodyPart = new MimeBodyPart();   //message part
    messageBodyPart.setContent(text, "text/html");

    Multipart multipart = new MimeMultipart();    //multipart
    multipart.addBodyPart(messageBodyPart);

    MimeBodyPart attachedPart = new MimeBodyPart();    //attachment part
    attachedPart.attachFile("c:\abc.pdf");
    multipart.addBodyPart(attachedPart);     

    emailMessage.setContent(multipart);
    emailSession.setDebug(true);
    Transport.send(emailMessage);