sending mail using java
SendMailSSL.java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL{
public static void main(String[] args) {
//from,password,to,subject,message
Mailer.send("mail address of sender","sender password","mail address of receiver","hello this is subject","How r u?");
//change from, password and to
}
}
class Mailer{
public static void send(final String from,final String password,String to,String sub,String msg){
//Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//get Session
try {
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
//compose message
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
//send message
Transport.send(message);
System.out.println("message sent successfully");
}
catch (MessagingException e)
{
System.out.println("invalid not working!!");
System.out.println("invalid not working!!");
}
}
}
Comments
Post a Comment