java - 添加附件包装在 Java 中的方法中

标签 java

我正在研究服务监视器,它会检查其他值以及 http 请求的 http 状态。一切正常,但我正在为我的代码寻找更智能的方法。 我正在使用的代码发送一封带有附件的邮件。但是,如果我不需要将附件 block 添加到每个 if 语句,那就太好了。
我已经搜索了一个可能的解决方案,但据我所知,我无法在方法中创建方法。 那么...有没有办法避免额外的代码行?附件 block 永远是相同的...

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

// define the class
class SendMailTLS {
    // define a method which recive your status code
    // instead of define main method
    public void sendMail(
    int httpStatus, ) {

        final String username = "sender@domain.com";
        final String password = "password";

        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() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sender@domain.com"));
            message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("recipients@domain.com"));


            message.setSubject("Status alert - Service");
            BodyPart messageBodyPart = new MimeBodyPart();

            if (httpStatus == 200) {
                messageBodyPart.setText("OK! The http Status is: " + httpStatus);

                //////////// AttachmentBlock START//////////
                // Create a multipar message
                Multipart multipart = new MimeMultipart();
                // Set text message part
                multipart.addBodyPart(messageBodyPart);
                // Part two is attachment
                String attachmentPath = "c:\\doms\\log.txt";
                messageBodyPart = new MimeBodyPart();
                FileDataSource source = new FileDataSource(attachmentPath);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(source.getFile().getName());
                multipart.addBodyPart(messageBodyPart);
                // Send the complete message parts
                message.setContent(multipart);
                //////////// AttachmentBlock END////////// 

                Transport.send(message);
            }

            if (httpStatus != 200) {
                messageBodyPart.setText("ERROR! The http Status is: " + httpStatus);

                //////////// AttachmentBlock START//////////
                // Create a multipar message
                Multipart multipart = new MimeMultipart();
                // Set text message part
                multipart.addBodyPart(messageBodyPart);
                // Part two is attachment
                String attachmentPath = "c:\\doms\\log.txt";
                messageBodyPart = new MimeBodyPart();
                FileDataSource source = new FileDataSource(attachmentPath);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(source.getFile().getName());
                multipart.addBodyPart(messageBodyPart);
                // Send the complete message parts
                message.setContent(multipart);
                //////////// AttachmentBlock END////////// 

                Transport.send(message);
            }

            //Transport.send(message)
            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the parameters
mailSender.sendMail(httpStatus);

最佳答案

您可以在您的类中创建一个private 方法来执行您需要的代码块:

class SendMailTLS {

     // method that contains the attachment block
     private void sendAttachment(BodyPart messageBodyPart) {
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        String attachmentPath = "c:\\doms\\log.txt";
        messageBodyPart = new MimeBodyPart();
        FileDataSource source = new FileDataSource(attachmentPath);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(source.getFile().getName());
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
     }

     public void sendMail(
         int httpStatus, )

         // ... your code

         if (httpStatus == 200) {
            messageBodyPart.setText("OK! The http Status is: " + httpStatus);
            // execute the private method here and anywhere else you want the same code to run
            sendAttachment(messageBodyPart);
         }

         // ... rest of the code
     }

此外,如前所述,您的 http 代码无效。您将代码 200 作为两个不同 if 语句中的条件,一个用于好的请求,一个用于坏的请求。我假设您的意思是第二个代码是 400 个范围代码之一(客户端错误代码)。

关于java - 添加附件包装在 Java 中的方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565356/

相关文章:

java - 为什么不将类序列化的定义放在共享包中会导致 `ClassNotFoundException` ?

java - 如何阻止 Maven 在每次项目运行时解包

java - 理解 dinic 算法有问题吗?

java - 选项 Pane 显示消息

java - 当输入只有整数和小数点部分时检查 double 值

java - Saxon:将 xdmNode 转换为 org.w3c.dom.Node

java - 有没有办法检查一个类是否有一个方法,然后在该对象的一个​​已经存在的实例上调用它?

java - 使用 postgres 和 jooq 按时间分组

java - 如何使用 JAVA 驱动程序 + SSH pem key 连接到 mongodb EC2 实例

java - 以增量方式存储文件