Tuesday, September 30, 2008

Sending email using GMAIL using Java Mail Api

Note: Search for changeme and replace with appropriate terms.





import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender {
final String senderEmailID = "changeme @ changeme .com";
final String senderPassword = "changeme";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
String emailSubject = null;
String emailBody = null;

public MailSender(String receiverEmailID, String emailSubject, String emailBody) {
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;


Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

SecurityManager security = System.getSecurityManager();

try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}


}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MailSender mailSender=new MailSender("changeme @ changeme .com","Test Mail from Puretechie","Here goes the body");
}

}

Monday, September 22, 2008

Common bad practice in database calculations

create table x ( i int, j varchar(10))
insert into x values (1,'a')
insert into `x`(`i`,`j`) values ( '2',NULL)


select count(*) from x
2
Select count(j) from x
1

Note the difference when the count(col_name) is used.

count(col_name) is used under the impression that it is faster than count(*) , however quite the opposite is true.

MYISAM table MySQL has cached number of rows in the table. Thats the reason why MYISM is able to instantly answer COUNT(*) query, but not COUNT(col_name).

Why ? Because say if col_name column is not defined as NOT NULL there can be some NULL values in it and so MySQL have to perform table scan to find out. This is also why result is different for the second query.

Using count(*) instead of count(col_name) falls in the best practice category.