I am trying to send error email through log4j. by using following appender:
<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>
but I am getting the following exception
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. wr9sm43519864pbc.7 - gsmtp
from several other question I understood that I need to add the following property in the smtpAppender
props.put("mail.smtp.starttls.enable", "true");
So how we can add it to the existing SMTPAppender ?
First way: you may extend SMTP appender and override createSession() method, where you can add any additional properties to Java Mail session, like aforementioned "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;
}
}
Second way: you may start your Java process with an option -Dmail.smtp.starttls.enable=true. This approach looks easier, but requires a control over JVM options; it also may be broken by too retrictive SecurityManager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With