2013-08-13 3 views
3

log4j를 통해 오류 전자 메일을 보내려고합니다. 다음 펜더 사용하여 :STARTTLS 명령을 실행해야합니다.

<appender name="ERROR_MAIL" class="org.apache.log4j.net.SMTPAppender"> 
    <param name="SMTPUsername" value="[email protected]" /> 
    <param name="SMTPPassword" value="**********" /> 
    <param name="To" value="[email protected]"/> 
    <param name="From" value="[email protected]"/> 
    <param name="Subject" value="Newyse Error "/> 
    <param name="SMTPHost" value="smtp.gmail.com"/> 
    <param name="SMTPPort" value="25" /> 
    <param name="BufferSize" value="10"/> 
    <layout class="org.apache.log4j.PatternLayout"> 
     <param name="ConversionPattern" value="[%d{ISO8601} %t %5p %c:$L]"/> 
    </layout> 
    <filter class="org.apache.log4j.varia.LevelRangeFilter"> 
     <param name="LevelMin" value="ERROR"/> 
     <param name="LevelMax" value="FATAL"/> 
    </filter> 
    </appender> 

을하지만 난 내가 smtpAppender

props.put("mail.smtp.starttls.enable", "true"); 

에 다음과 같은 속성을 추가 할 필요가 있음을 이해 몇 가지 다른 질문에서 다음과 같은 예외

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. wr9sm43519864pbc.7 - gsmtp 

무엇입니까 기존 SMTPAppender에 어떻게 추가 할 수 있습니까?

답변

1

@ Jk1에게 많은 감사를드립니다.이 질문에 언급 된 구성을 사용하여 작업 코드를 얻으려는 응답을 받았습니다.

import java.util.Date; 
import java.util.Properties; 

import javax.mail.Authenticator; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMultipart; 

import org.apache.log4j.Layout; 
import org.apache.log4j.helpers.LogLog; 
import org.apache.log4j.net.SMTPAppender; 
import org.apache.log4j.spi.LoggingEvent; 

import com.sun.mail.smtp.SMTPTransport; 

/** 
* Extension of Log4j {@link SMTPAppender} for Gmail support 
* 
*/ 
public class SecureSMTPAppender extends SMTPAppender 
{ 
    /** 
    * Cached session for later use i.e. while sending emails 
    */ 
    protected Session session; 

    public SecureSMTPAppender() 
    { 
    super(); 
    } 

    /** 
    * Create mail session. 
    * 
    * @return mail session, may not be null. 
    */ 
    protected Session createSession() 
    { 
    Properties props = new Properties(); 
    props.put("mail.smtps.host", getSMTPHost()); 
    props.put("mail.smtps.auth", "true"); 

    Authenticator auth = null; 
    if (getSMTPPassword() != null && getSMTPUsername() != null) 
    { 
     auth = new Authenticator() 
     { 
     protected PasswordAuthentication getPasswordAuthentication() 
     { 
      return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword()); 
     } 
     }; 
    } 
    session = Session.getInstance(props, auth); 
    if (getSMTPDebug()) 
    { 
     session.setDebug(getSMTPDebug()); 
    } 
    return session; 
    } 

    /** 
    * Send the contents of the cyclic buffer as an e-mail message. 
    */ 
    protected void sendBuffer() 
    { 
    try 
    { 
     MimeBodyPart part = new MimeBodyPart(); 

     StringBuffer sbuf = new StringBuffer(); 
     String t = layout.getHeader(); 
     if (t != null) 
     sbuf.append(t); 
     int len = cb.length(); 
     for (int i = 0; i < len; i++) 
     { 
     LoggingEvent event = cb.get(); 
     sbuf.append(layout.format(event)); 
     if (layout.ignoresThrowable()) 
     { 
      String[] s = event.getThrowableStrRep(); 
      if (s != null) 
      { 
      for (int j = 0; j < s.length; j++) 
      { 
       sbuf.append(s[j]); 
       sbuf.append(Layout.LINE_SEP); 
      } 
      } 
     } 
     } 

     t = layout.getFooter(); 
     if (t != null) 
     sbuf.append(t); 
     part.setContent(sbuf.toString(), layout.getContentType()); 

     Multipart mp = new MimeMultipart(); 
     mp.addBodyPart(part); 
     msg.setContent(mp); 

     msg.setSentDate(new Date()); 
     send(msg); 
    } catch (Exception e) 
    { 
     LogLog.error("Error occured while sending e-mail notification.", e); 
    } 
    } 

    /** 
    * Pulled email send stuff i.e. Transport.send()/Transport.sendMessage(). So 
    * that on required this logic can be enhanced. 
    * 
    * @param msg 
    *   Email Message 
    * @throws MessagingException 
    */ 
    protected void send(Message msg) throws MessagingException 
    { 
    SMTPTransport t = (SMTPTransport) session.getTransport("smtps"); 
    try 
    { 
     t.connect(getSMTPHost(), getSMTPUsername(), getSMTPPassword()); 
     t.sendMessage(msg, msg.getAllRecipients()); 
    } finally 
    { 
     System.out.println("Response: " + t.getLastServerResponse()); 
     t.close(); 
    } 
    } 
} 
+4

누군가가 대답을하기 위해 시간을 들여 문제를 해결하기 위해 자신의 대답을 취할뿐만 아니라 자신의 대답을 기반으로 대답을 추가 한 다음 자신의 대답을 수락합니까? 야, 그게 BS 야 ... 나는 그럴거야. –

11

첫 번째 방법 : 당신은 SMTP의 펜더를 확장하고 createSession 당신이 언급 한 "mail.smtp.starttls.enable"

public class SecureSMTPAppender extends SMTPAppender { 

    private boolean useStartTLS; 

    public void setUseStartTLS(boolean useStartTLS) { 
     this.useStartTLS = useStartTLS; 
    } 

    @Override 
    protected Session createSession() { 
     Properties props = null; 
     try { 
      props = new Properties(System.getProperties()); 
     } catch (SecurityException ex) { 
      props = new Properties(); 
     } 
     if (getSMTPHost() != null) { 
      props.put("mail.smtp.host", getSMTPHost()); 
     } 
     if (useStartTLS) { 
      props.put("mail.smtp.starttls.enable", "true"); 
     } 
     Authenticator auth = null; 
     if (getSMTPPassword() != null && getSMTPUsername() != null) { 
      props.put("mail.smtp.auth", "true"); 
      auth = new Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword()); 
       } 
      }; 
     } 
     Session session = Session.getInstance(props, auth); 
     if (getSMTPDebug()) { 
      session.setDebug(true); 
     } 
     return session; 
    } 
} 
처럼, 자바 메일 세션에 추가 속성을 추가 할 수 있습니다() 메소드를 오버라이드 (override)

두 번째 방법 : -Dmail.smtp.starttls.enable = true 옵션을 사용하여 Java 프로세스를 시작할 수 있습니다. 이 접근법은 더 쉬워 보이지만 JVM 옵션을 제어해야합니다. 너무 엄격한 SecurityManager에 의해 손상 될 수도 있습니다.

+0

감사합니다.이 속성을 xml 구성 파일에서 설정할 수 있습니까? –

+0

SMTPAppender는 매우 원시적이며 log4j.xml 또는 log4j.properties를 통해 tls 관련 구성을 지원하지 않습니다. – Jk1

관련 문제