简体   繁体   English

为具有附件的电子邮件设置分段

[英]Setting Multipart for email that has attachment

From my application i am send mails that has attachments. 从我的应用程序中,我将发送包含附件的邮件。 the complete code is here 完整的代码在这里

public int sendMail(MailDraft mailDraftInstance, mailInstance, path){                               //Send the mail
    String mailSubject  = mailDraftInstance.subject
    String toAddress    = mailDraftInstance.toAddress
    String ccAddress    = mailDraftInstance.ccAddress
    String bccAddress   = mailDraftInstance.bccAddress
    String fromAddress  = mailDraftInstance.fromAddress
    String body         = mailDraftInstance.body

    String smtpUsername = 'myusername'
    String smtpPassword = 'mypwd'

    /*** set the SMTP properties and Authenticate*****/
    Properties smtpMailProperties
    Session mailSession
    smtpMailProperties = mailInstance.getSmtpConnectionProperties()
    mailSession = mailInstance.getMailSession(smtpMailProperties, smtpUsername, smtpPassword)

    try {

        /**** Set the Header *************/
        User loggedInUser = User.get(SecurityContextHolder.context.authentication.principal.id)
        Address address = new InternetAddress(mailDraftInstance.fromAddress);
        Address replyAddress = new InternetAddress(mailDraftInstance.fromAddress);
        Message message = new MimeMessage(mailSession);
        message.setFrom(address); 
        //message.addFrom(address); //Set the from address with the logged in user email
        message.setReplyTo(replyAddress)

        /*** set Recipients*********/
        String recipientType = 'TO'
        setMailRecipients(message, toAddress, recipientType, toAddressError)
        recipientType = 'CC'
        setMailRecipients(message, ccAddress, recipientType, ccAddressError)
        recipientType = 'BCC'
        setMailRecipients(message, bccAddress, recipientType, bccAddressError)

        message.setSubject(mailSubject);    

        Multipart multiPart = new MimeMultipart("alternative");   // Create an "Alternative" Multipart message
        // Multipart multiPart = new MimeMultipart("mixed");


        MimeBodyPart text = new MimeBodyPart();
        MimeBodyPart html = new MimeBodyPart();

        text.setText(body.replaceAll("\\<[^>]*>","").replaceAll("&nbsp;"," ").replaceAll("&amp;","&"));  //set the text/plain version
        html.setContent(Jsoup.parse(body).html(), "text/html");     //set the text/html version

        multiPart.addBodyPart(text);
        multiPart.addBodyPart(html);


        /*  // Set the Body 
        Multipart multiPart = new MimeMultipart();
        MimeBodyPart messageHtml = new MimeBodyPart();  //Create a mime body 
        messageHtml.setContent(body, "text/html");      //set the content type as HTML
        multiPart.addBodyPart(messageHtml);*/

        // Add the Attachments
        if(!mailDraftInstance.attachments.isEmpty()){
            Mail.attachFiles(mailDraftInstance.attachments, multiPart, path)
        }  
        int i=0;
        mailDraftInstance.attachments.each{
            i++
        }
        message.setContent(multiPart);      //set the content
        Transport.send(message);            //send the mail
    }catch (Exception e) {
        if(e instanceof AddressException){
            println "Email Recipient Address error"                             //Error with the TO Or CC Or BCC Adresss
            return addressErrorType
        }else{
            println e                                                           //Other errors, may be with the SMTP server
            println "Cannot send email as an error occurred"
            return addressErrorType
        }
    }
    return mailSentSuccessfully    //mail sent successfully
}



  public static attachFiles(def attachments, Multipart multiPart, String path){                     //Attach files
    attachments.each {

        def attachmentId = it.id
        String newFile= TrainingService.createFile(attachmentId, path)

        MimeBodyPart fileAttachmentPart = new MimeBodyPart();
        FileDataSource attachmentfile = new FileDataSource(newFile);
        fileAttachmentPart.setDataHandler(new DataHandler(attachmentfile));
        println "newFile============="+attachmentfile.getName()
        fileAttachmentPart.setFileName(attachmentfile.getName());
        multiPart.addBodyPart(fileAttachmentPart);

    }

}

if i set 如果我设置

  Multipart multiPart = new MimeMultipart("alternative"); 

some of the clients (yahoomail) does not receive attachments.. 一些客户端(yahoomail)没有收到附件。

so should be the Multipart setting to receive email that has got both text, html and attachments? 所以“多部分”设置应该可以接收同时包含文本,html和附件的电子邮件吗?

Try this: 尝试这个:

     public int sendMailWithSingleAttachment(String to, String subject, String body, String fileName, String sendFileName) {
    final String username = "Your Username";
    final String password = "Your Password";
    Properties props = new Properties();
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.host", "smtp.live.com");
    props.put("mail.smtp.port", "25");
    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");
    props.setProperty("mail.smtp.port", "587");
    props.setProperty("mail.smtp.socketFactory.port", "587");
    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<html>hello</html>", "text/html");
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(sendFileName);
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);
        Transport.send(message);

        return 1;
    } catch (Exception e) {


        return 0;
    }
}

Please use the port according to your service provider, I am using outlook. 请根据您的服务提供商使用端口,我正在使用Outlook。 The library used is java mail . 使用的库是java mail

If you want a message contains both alternative parts and attachments, you need two multiparts, one nested in the other. 如果您希望邮件同时包含其他部分和附件,则需要两个多部分,一个嵌套在另一个中。 The outer multipart should be multipart/mixed. 外部多部分应该是多部分/混合的。 The first body part of that multipart should be a multipart/alternative part. 该多部分的第一主体部分应为多部分/替代部分。 The second body part of the outer multipart should be the attachment. 外部多部分的第二个主体部分应该是附件。 The inner multipart contains the plain text and html body parts. 内部多部分包含纯文本和html正文部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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