java发送email

以下是java发送email的代码:

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

public class HFEmail {

private static final Logger log = Logger.getLogger(HFEmail.class);

public static void sendSystemEmail(String to, String subject,
String bodyContent) throws HFEmailException {
sendEmail(HFConfig.getInstance().getMailFrom(), to, subject, bodyContent);
}

public static void sendEmail(String from, String to, String subject,
String bodyContent) throws HFEmailException {
try {   
    Properties props = System.getProperties();
    props.put("mail.smtp.host", HFConfig.getInstance().getMailServerHost());
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(HFConfig
.getInstance().getMailUsername(), HFConfig
.getInstance().getMailPassword());
}
});
    MimeMessage message = new MimeMessage(session); 
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO,
      new InternetAddress(to));
   
    message.setSubject(subject);    
    message.setContent(bodyContent, "text/html;charset=utf-8");

    message.saveChanges();
    Transport.send(message);
} catch (Exception e) {
log.error("Email send error! From: " + from + ", To: " + to, e);
throw new HFEmailException(e);
}
}

}

你可能感兴趣的:(java,apache,html,log4j)