RSS feed

Sending Email from JSP Pages Using smtp.gmail.com

Sample Codes for Sending Emails from JSP Page Using Gmail

Published by: San (9/4/2007)

SEP 4 2007

How can I send emails from a jsp page? I have a page where i have a form and it sends out emails on submition. Please let me know the code and classes to include in jsp page to send emails.

This works for me. Try on your jsp page and if it doesn't work then post a comment here. Make sure to use the correct smtp server, user id and password. It can send text and html type of content so better comment and uncomment the codes on your wish.

String host="", user="", pass="";
host = smtp_server; //"smtp.gmail.com"; user = jsp_email; //"YourEmailId@gmail.com" // email id to send the emails
pass = jsp_email_pw; //Your gmail password
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String to = email_to_address; // out going email id
String from = email_from_address; //Email id of the recipient
String subject = email_subject;
String messageText = email_body;
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setContent(messageText, "text/html"); // use setText if you want to send text
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
try {
transport.sendMessage(msg, msg.getAllRecipients());
WasEmailSent = true; // assume it was sent
}
catch (Exception err) {
WasEmailSent = false; // assume it's a fail
}
transport.close();

 

Javascript Change Image onMouseOver >>

<< JSP Web Services Example - XML, XSLT in JSP - XML Web Services in Java

 

COMMENT

*Name:
*Comment:
You can use HTML tags here.
*Code: Please enter the sum of 5+2