Sunday 23 January 2011

Sending Mail Using Java Mail API







import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class MailSend
{
public static void SendMail(String to)throws MessagingException
{
String subject="Thanks";
boolean bodyIsHTML=false;
String body="thanks for registration";
String from="SendermailId";//abc@gmail.com
Properties props=new Properties();
props.put("mail.transport.protocol","smtp");
System.setProperty("mail.smtps.auth", "true");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port",25);
props.put("mail.smtp.auth","true");
props.put("mail.smtp.starttls.enable","true");


Session session=Session.getDefaultInstance(props);
session.setDebug(true);
//create message
Message message=new MimeMessage(session);
message.setSubject(subject);
if(bodyIsHTML)
message.setContent(body,"text/html");
else
message.setText(body);
//Address the Messsage
Address frmAdd=new InternetAddress(from);
Address toAdd=new InternetAddress(to);
// if u send to some user to cc then use below code
//here xyz is the address of recivers

Address ccAdd[]={new InternetAddress("xyz@m.com"),new InternetAddress("xyz@m.com"),new InternetAddress("xyz@m.com")};
message.setFrom(frmAdd);

// In case of Bcc use BCC
message.setRecipient(Message.RecipientType.TO,toAdd);
// In case of cc use CC
message.addRecipients(Message.RecipientType.CC, ccAdd);
//Send Message
Transport transport = session.getTransport();
transport.connect("smtp.gmail.com", 25,"abc@gmail.com","password");
transport.sendMessage(message,message.getAllRecipients());
}
public static void main(String a[])
{String s="reciever email address";
try{
SendMail(s);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

No comments:

Post a Comment