简体   繁体   English

使用log4j.smtpAppender发送电子邮件附件

[英]email attachments using log4j.smtpAppender

can i trigger an email with attachment(log files) using the log4j.smtpAppender. 我可以使用log4j.smtpAppender触发带附件(日志文件)的电子邮件。

I'm currently using this appender to trigger emails for error and fatal level exceptions. 我目前正在使用此appender来触发错误和致命级别异常的电子邮件。 Can I add the log file in the same email as attachment 我可以在与附件相同的电子邮件中添加日志文件吗?

log4j.appender.email=org.apache.log4j.net.SMTPAppender

I think you can't send a log file in the same email. 我想你不能在同一封电子邮件中发送日志文件。 You can of course configure several appenders to log your data: example one sending email (SMTPAppender), other printing to stdout (ConsoleAppender), etc. 您当然可以配置多个appender来记录您的数据:例如,发送电子邮件(SMTPAppender),其他打印到stdout(ConsoleAppender)等。

Besides, I don't think it is a good idea to attach a log file to the same email: the log file will keep growing each time a new email is sent, and suppose your log is about 5MB long...then logging will eat you a big chunk of processing power. 此外,我认为将日志文件附加到同一封电子邮件不是一个好主意:每次发送新电子邮件时日志文件都会不断增长,并假设您的日志长度约为5MB ...然后记录将给你一大块处理能力。

public static void emailAttachment
              throws AddressException, MessagingException{

  String host = mail.company.com;
  String from = user@company.com;
  String to = user2@company.com;
  String cc = user3@company.com;

  Properties props = System.getProperties();

  props.put("mail.smtp.host", host);
  Session session = Session.getInstance(props, null);

  MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));

  message.setSubject("Email Notification");
  MimeBodyPart messageBodyPart = new MimeBodyPart();

  messageBodyPart.setText("email Body");

  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart);
  messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(fileAttachment);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName("attachment.pdf");
  multipart.addBodyPart(messageBodyPart);

  message.setContent(multipart);

  Transport.send( message );

}

Source: jGuru.com 资料来源: jGuru.com

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

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