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

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);
}

Related

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);
}
}

Can't send mail using JavaMail due to javax.mail.AuthenticationFailedException

I'm trying to configure my app to send mail, using gmail. I looked up the gmail javamail documentation and I've been able to write that piece of code:
String from = mymail;
String pass = mypass;
String[] to = { somemail }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
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.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
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();
}
but I keep getting the following error:
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.c....
What should I try to change ?
It may be that Gmail account is not configured to use less secure authentication. You can change that by logging into the account you are trying to send email from and then going to this page. On that page you can turn on access by less secure authentication. This should solve the problem

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 mail using java from pc to mobile

final String username = "<mail_name>";
final String password = "<password>";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<mail_from>#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>#gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
I have tried this code for sending mail from pc to mobile but it giving error while compiling . Can any one help me to send mail?
public class sendmail{
public static void mail(String args[]){
final String fromEmail = ""; //requires valid gmail id
final String password = ""; // correct password for gmail id
final String toEmail = "" // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
String subject = "";//subject here
String body = "";//mail body here
sendEmail(session, toEmail, subject, body);
}
public static void sendEmail(Session session, String toEmail, String subject, String body) {
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no-reply#anyname.com", "any name"));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR:" + e.getMessage());
}
}
}
What is mean by PC to Mobile. PC & mobile both are hardware devices to access the mail.Please follow the below link for sending mail in java using java mail API via gmail SMTP.
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Cpanel Java Email Client Program

If anyone tried/found working java email/smtp/imap client program that connects to cPanel's email a/cs and send emails out then please share it. It has been a tiresome efforts in trying to find that code online but none of them works fine. I did try more than five varieties of code but nothing worked. Below are few samples:
Sample# 1
String host = "mail.domain.net";
String user = "catch-all#domain.net";
String pass = "xxxx";
String to = "admin#domain.net";
String from = "catch-all#domain.net";
String subject = "Dummy subject";
String messageText = "Dummy body";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", 2525); //25 - default
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
Error
Sending mail.. Done!javax.mail.MessagingException: Could not connect to SMTP host: mail.dealstock.net, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:192)
at com.mail.EmailsSender2.main(EmailsSender2.java:209)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mai
From the Cpanel account, the designated port is 2525, if secured then 465, but none of the ports work. With post 2525, it does connects, but there is no response and waits for 1-2 minitues and then timeouts. If I change to port 25, then it simply throws above error. With same Cpanel email a/c my another program able to connect and read emails through POP, but failing with sending emails.
Appreciate if you can share your comments/inputs.
I have hostgator, and when creating session, use the following code it works (with no encryption or SSL, not TLS).
btw, port 25 is blocked by my isp (Verizon), and hostgator has it on port 26, not 2525. make sure your hosting company has it running on 2525.
private Session getSession(final EmailConfig emailConfig) {
String port = Integer.toString(emailConfig.getPort());
Properties props = new Properties();
props.put("mail.smtp.host", emailConfig.getHost());
props.put("mail.smtp.port", port);
if (Encryption.SSL == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (Encryption.TLS == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
}
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getDecryptedPassword());
}
});
}
private void sendMessage(Session session, InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String text) throws AuthenticationFailedException {
Message message = new MimeMessage(session);
try {
message.setFrom(from);
if (to != null) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (cc != null) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (bcc != null) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
catch (AuthenticationFailedException ex) {
log.info("authentication failed", ex);
throw ex;
}
catch (MessagingException e) {
log.info("error sending message", e);
e.printStackTrace();
}
}
This would definitely work for you.
Just call this function to send automated email to client.
In parameter "to" is email address to which you want to send an email.
I usually do it in Maven project. If you are using maven project then import following dependencies.
https://mvnrepository.com/artifact/javax.mail/mail/1.4
final String username = "youremail#gmail.com";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("youremail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

Categories