首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Add- Java中封装在方法中的附件

Add- Java中封装在方法中的附件
EN

Stack Overflow用户
提问于 2015-02-17 23:47:28
回答 1查看 199关注 0票数 2

我正在处理一个服务监视器,它检查http-request的http-Status的其他值。一切工作正常,但我正在为我的代码寻找更智能的方式。我使用的代码发送带有附件的邮件。但是,如果我不需要在每个if语句中添加附件块,那就太好了。

我已经寻找了一种可能的解决方案,但就我所见,我不能在方法中创建方法。So...is有没有办法避免额外的代码行?附件块总是相同的……

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

发布于 2015-02-17 23:56:33

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

代码语言:javascript
复制
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代码是无效的。在两个不同的if语句中有代码200be条件,一个用于好的请求,另一个用于坏的请求。我假设你的意思是第二个代码是400个范围中的一个(客户端错误代码)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28565356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档