working with JavaMailApi in jsp - java

i working with registration page in this i need to send to a verification link to mail,while executing a got error and saying that java.net.ConnectException: Connection refused: connect
so please help me thanku
register.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>REGISTRATION</title>
</head>
<body>
<%!
DBCreation creation;
Connection connection;
%>
<%
String uid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
String fName=request.getParameter("fname");
String lName=request.getParameter("lname");
String email=request.getParameter("email");
String location=request.getParameter("location");
String encpwd=encryptPwd(pwd);
System.out.println(encpwd);
connection=DBCreation.getConnection();
String result;
// Recipient's email ID needs to be mentioned.
String toEmail = email;
// Sender's email ID needs to be mentioned
String fromEmail = "nbarath2008#gmail.com";
// Assuming you are sending email from localhost
//String host = "localhost";
// Get system properties object
Properties properties = System.getProperties();
// Setup mail server
// properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session mailSession = Session.getDefaultInstance(properties);
Transport transport = new SMTPTransport(mailSession,new URLName("localhost"));
transport.connect("localhost",25,null,null);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,""+email);
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
result = "Sent message successfully....";
PreparedStatement statement=connection.prepareStatement("insert into userregistration values(?,?,?,?,?,?,?)");
statement.setString(1,uid);
statement.setString(2,encpwd);
statement.setString(3,fName);
statement.setString(4, lName);
statement.setString(5, location);
statement.setString(6, fromEmail);
statement.setString(7, toEmail);
int i=statement.executeUpdate();
if(i>0)
{
// Send message
Transport.send(message);
result = "Sent message successfully....";
RequestDispatcher rd=request.getRequestDispatcher("regsuccess.jsp");
rd.forward(request, response);
}
}catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>

This is the working code. Please ask you have any doubts!
import java.util.;
import javax.mail.;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "gmail-user-name"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "******"; // Enter your GMail password
private static String RECIPIENT = "RECIPIENT EMAIL address";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Related

How can I send email to user after Registration [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on user registration function.Now I headed a new problem.
I want to send an Email to user after user done with the Registration.
#PostMapping("registration")
public String registration(Model model,
#Valid #ModelAttribute("cool") User user,
BindingResult bindingresult) {
if (bindingresult.hasErrors()) {
model.addAttribute("cool", user);
return "registration";
}
model.addAttribute("user", user);
data.addUser(user);
//------------------------Email----------------//
// Here I need a solution
//------------------------Email----------------//
return "success";
}
For example:
my Email Address is: Vincent#gmail.com
I want to send an Email from my Email(or from localhost) to User's Email.
You can use Gmail SMTP via TLS
private static String USER_NAME = "Gmail Username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "gbxxfgfhujdfqndd"; // GMail password
public static boolean sendEmail(String RECIPIENT, String sub, String title, String body, String under_line_text,
String end_text) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = {
RECIPIENT
}; // list of recipient email addresses
String subject = sub;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<div style=\" background-color: white;width: 25vw;height:auto;border: 20px solid grey;padding: 50px;margin:100 auto;\">\n" +
"<h1 style=\"text-align: center;font-size:1.5vw\">" + title + "</h1>\n" + "<div align=\"center\">" +
"<h2 style=\"text-align: center;font-size:1.0vw\">" + body + "</h2>" +
"<h3 style=\"text-align: center;text-decoration: underline;text-decoration-color: red;font-size:0.9vw\">" +
under_line_text + "</h3><br><h4 style=\"text-align: center;font-size:0.7vw\">" + end_text +
" </h4></div>";
messageBodyPart.setContent(htmlText, "text/html");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException ae) {
ae.printStackTrace();
} catch (MessagingException me) {
me.printStackTrace();
}
return true;
}
Or Gmail via SSL in which you should add
//change port number
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Output:
Also you can change BodyPart accordingly i have included an html responsive template
I recommend you to visit your Google Account and generate a new Application Password , this allows your password field to be encoded and not used as plain text
Otherwise you will come up with this exception
javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required.
Hope it helped!
String host = "smtp.gmail.com";
int port = 587;
final String username = "xxxx#gmail.com";
final String password = "your password";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", port);
Session session = Session.getInstance(props,new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}} );
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("aaaa#trend.com.tw"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,\n\n No spam to my email, please!");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

How to send java mail in spring mvc

I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}

Read HTML file and send it as html formatted email

I want to read HTML file and want to send HTML formatted email.
public class SendEmailer {
public void sendHtmlEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// sets SMTP server properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.store.protocol","pop3");
properties.put("mail.transport.protocol","smtp");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// set plain text message
msg.setContent(message, "text/html");
// sends the e-mail
Transport.send(msg);
}
//Code to read HTML document.
public void readHTML(String strfilename,String content){
// content="";
String str="";
try{
FileReader fr=new FileReader(strfilename);
BufferedReader br=new BufferedReader(fr);
while((str=br.readLine())!=null){
System.out.println(str.toString());
content+=str;
}
br.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) {
// SMTP server information
String host = "myhost.com";
String port = "465";
String mailFrom = "abc#myhost.com";
String password = "abcd123";
// outgoing message information
String mailTo = "abc#gmail.com";
String subject = "Test mail";
// message contains HTML markups
String message = "<i>Greetings!Sending HTML mail.</i><br>";
message += "<font color=red>MyName</font>";
SendEmailer mailer = new SendEmailer ();
String filename="E:/filepath/filename.html";
try {
mailer.readHTML(filename);
mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
subject, message);
System.out.println("Email sent successfully.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
I am able to send email successfully. But now I want to send the full body part of the html file. I wrote a method readHTML(), but its not reading the content of that file neither it sends the same. It sends only what I've stored in message variable. Where did I make mistake?

JavaMail API Error (javax.mail.NoSuchProviderException: invalid provider)

I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Sending Email with Java..Attachment code not working?

I have just tried to send an email through java code. Actually it works fine with no errors at all.But when i recieve email it does not contain attachment which according to the code should be there("try.txt").
I have no idea at all about JavaMail i just gone through this code and tried this
Code Here
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "******"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "*******"; // GMail password
private static String RECIPIENT = "*******";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Find An Attachment";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
//session.setDebug(true);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//attachment
messageBodyPart = new MimeBodyPart();
String filename = "C:/try.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Something special need to be added for an attachment to be sent properly ?
Please guide me.
Thanks in advance
Remove this line from your code
message.setText(body);
setText() internally calls setContent() function. So if you call setText() function after you setContent, it basically over-rides the content you initially set.
See this for more Information.
Try this:
MimeBodyPart mimeBody = new MimeBodyPart();
mimeBody.attachFile(file);
MimeMultipart mimeMulti = new MimeMultipart();
mimeMulti.addBodyPart(mimeBody);
msg.setContent(mimeMulti);
I faced similar challenges sending email with attachments programatically. I used Apache Commons Email like this:
public static final String ATTACHMENT_PATH = "/opt/testfile/example_4mb_file.mp4";
// Create the attachment
File attachFile = new File(ATTACHMENT_PATH);
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(attachFile.getAbsolutePath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(attachFile.getName());
attachment.setName(attachFile.getName());
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(
EMAIL_USERNAME,
EMAIL_PASSWORD));
email.setSSLOnConnect(true);
email.addTo(EMAIL_RECEIVER);
email.setFrom(EMAIL_SENDER, EMAIL_SUBJECT);
email.setSubject("TestMail id " + this.uniqueId);
email.setMsg("This is a test attachment mail ... :-)");
// add the attachment
email.attach(attachment);
// send the email
email.send();

Categories