HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sending HTML-formatted mail in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sendingjavaformattedmailhtml

Problem

This is my code for sending mail in HTML format:

```
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public void sendMail(String m_from,String m_to,String m_subject,String m_body){
try {
Session m_Session;
Message m_simpleMessage;
InternetAddress m_fromAddress;
InternetAddress m_toAddress;
Properties m_properties;

m_properties = new Properties();
m_properties.put("mail.smtp.host", "smtp.gmail.com");
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
m_properties.put("mail.smtp.auth", "true");
m_properties.put("mail.smtp.port", "465");

m_Session=Session.getDefaultInstance(m_properties,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx","yyyyy"); // username and the password
}
});

m_simpleMessage = new MimeMessage(m_Session);
m_fromAddress = new InternetAddress(m_from);
m_toAddress = new InternetAddress(m_to);
m_simpleMessage.setFrom(m_fromAddress);
m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);
m_simpleMessage.setSubject(m_subject);

m_simpleMessage.setContent(m_body, "text/html");
//m_simpleMessage.setContent(m_body,"text/plain");

Transport.send(m_simpleMessage);
} catch (MessagingException ex) {
ex.printSta

Solution

-
Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.

See Effective Java, Second Edition, Item 45: Minimize the scope of local variables. (Google for "minimize the scope of local variables", it's on Google Books too.))

-
The m_ prefix is unnecessary and uncommon in the Java world. See Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions

-
The sendMail method should validate its input parameters. Does it make sense if the form, to etc. is null or empty string? If not, check it and throw a NullPointerException or an IllegalArgumentException. (Effective Java, Second Edition, Item 38: Check parameters for validity)

Context

StackExchange Code Review Q#12529, answer score: 3

Revisions (0)

No revisions yet.