Email verification in grails - grails

I am new with grails and am developing a web application in grails.
In my registration page I am getting the user's email id and I need to send a mail with authentication link.
http://grails.org/plugin/mail
http://grails.org/plugin/email-confirmation
I have referred these pages and many other pages to do this task.
But the problem is, my email is not sending.
I have used
Gmail SMTP server address : smtp.gmail.com
Gmail SMTP username : myid#gmail.com
Gmail SMTP password : -my password-
Gmail SMTP port : 465
Gmail SMTP TLS/SSL required : yes
Mail settings are:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "myId#gmail.com"
password = "mypassword"
props = [
"mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class": "javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
grails.mail.default.from="noreply#gmail.com"
but at least
sendMail {
to "friend#gmail.com"
subject "Hello "
body 'How are you?'
}
is not working.
The exception occured is
Error 500: Internal Server Error
URI
/MailVerificationDemo/user/signup/form
Class
java.net.ConnectException
Message
Connection refused
Around line 104 of MailMessageBuilder.groovy
101: log.trace("Sending mail ${getDescription(message)}} ...")102: }103:104: mailSender.send(message instanceof MimeMailMessage ? message.mimeMessage : message)105:106: if (log.traceEnabled) {107: log.trace("Sent mail ${getDescription(message)}} ...")
Around line 41 of grails-app/services/grails/plugin/mail/MailService.groovy
38: callable.resolveStrategy = Closure.DELEGATE_FIRST39: callable.call()40:41: messageBuilder.sendMessage()42: }43:44: def getMailConfig() {
Around line 18 of grails-app/controllers/user/UserController.groovy
15: return16: }17:18: mailService.sendMail {19: to userInstance.email20: subject "New User Confirmation"21: html g.render(template:"mailtemplate",model:[code:userInstance.confirmCode])
Around line 195 of PageFragmentCachingFilter.java
192: if (CollectionUtils.isEmpty(cacheOperations)) {193: log.debug("No cacheable annotation found for {}:{} {}",194: new Object[] { request.getMethod(), request.getRequestURI(), getContext() });195: chain.doFilter(request, response);196: return;197: }198:
Around line 63 of AbstractFilter.java
60: try {61: // NO_FILTER set for RequestDispatcher forwards to avoid double gzipping62: if (filterNotDisabled(request)) {63: doFilter(request, response, chain);64: }65: else {66: chain.doFilter(req, res);

Try this it's worked for me.
Notice that: Gmail SMTP TLS/SSL required : yes.
But you don't put "mail.smtp.starttls.enable": "true"
grails.mail.host="smtp.gmail.com"
grails.mail.port=587
grails.mail.username="yourUsernameHere"
grails.mail.password="yourPwdHere"
grails.mail.from="defaultMailFromHere"
grails.mail.props = ['mail.smtp.auth': "true",
"mail.smtp.starttls.enable": "true",
"mail.from":"defaultMailFromHere"]
grails.mail.javaMailProperties = ['mail.smtp.auth': "true",
"mail.smtp.starttls.enable": "true",
"mail.from":"defaultMailFromHere"]

Related

PHPMailer dev-xoauth failed authentication

So I've gone through all of the docs on github - phpmailer xoauth tree to set up my scripts accordingly to use Google's oauth2. I am trying to send an email from the form at halcyonco.io to myself. The domain name is just to live test this site. I encounter the same error when sending the form locally.
My question is when I submit the form I receive this error:
SERVER -> CLIENT: 220 mx.google.com ESMTP pj4sm27148656pbb.29 - gsmtp
CLIENT -> SERVER: EHLO halcyonco.io
SERVER -> CLIENT: 250-mx.google.com at your service, [68.65.121.206]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
CLIENT -> SERVER: EHLO halcyonco.io
SERVER -> CLIENT: 250-mx.google.com at your service, [68.65.121.206]
250-SIZE 35882577250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN XOAUTH
250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING
250 SMTPUTF8
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SERVER -> CLIENT: 221 2.0.0 closing connection pj4sm27148656pbb.29 - gsmtp
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
I have been in touch with Namecheap as I have my hosting and domains through them but after an hour and half they could not help me.
Below is my contact.php script
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["user_name"]);
$email = trim($_POST["user_email"]);
$comment = trim($_POST["comment"]);
if ($name == "" OR $email == "" OR $comment == "") {
echo '<h3>Please fill out all forms.</h3>';
exit;
}
// SPAM protection
foreach ($_POST as $value) {
if ( stripos($value, 'Content-Type') !== FALSE ) {
echo "There was a problem with the information you entered.";
exit;
}
}
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('America/New_York');
require '../vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
//Load dependnecies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailerOAuth;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType
$mail->AuthType = 'XOAUTH2';
//User Email to use for SMTP authentication - Use the same Email used in Google Developer Console
$mail->oauthUserEmail = "myemail#gmail.com";
//Obtained From Google Developer Console
$mail->oauthClientId = "1234567890.apps.googleusercontent.com";
//Obtained From Google Developer Console
$mail->oauthClientSecret = "123456789";
//Obtained By running get_oauth_token.php after setting up APP in Google Developer Console.
//Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
// eg: http://localhost/phpmail/get_oauth_token.php
$mail->oauthRefreshToken = "1/ABCD12345EFGH6789";
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, $name);
//Set who the message is to be sent to
$mail->addAddress('myemail#gmail.com', 'Brandon Smith');
//Set the subject line
$mail->Subject = 'Promethean Fitness Enquiry | ' . $name;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML = $comment;
//Replace the plain text body with one created manually
$mail->Body = $comment;
$mail->AltBody = $comment;
//Attach an image file
//send the message, check for errors
if (!$mail->send()) {
echo '<h3>Please ensure you have entered a correct email address.</h3><br>';
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header("Location: ../html/thanks.html");
exit;
}
//This is a spam protection
if ($_POST["user_address"] != "") {
echo "Your form submission has an error";
exit;
}
}
?>
Any help on what I need to do in order to fix this would be great.

"Unrecognized SSL message, plaintext connection" during send mail using grails async mail api

I am trying to send mail using Grails Async Mail API
When I tried for Gmail using below configuration :
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "xxxx#gmail.com"
password = "xxxx"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
in config.groovy, I was able to send mail. When I changed above configuration for a specific mail server as below :
grails {
mail {
host = "xxx"
port = 25
username = "xxx"
props = ["mail.smtp.auth":"false",
"mail.smtp.socketFactory.port":"25",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"true",
"mail.smtp.starttls.enable": "false",
"mail.smtp.starttls.required": "false"]
}
}
I am getting below error :
javax.mail.MessagingException: Could not connect to SMTP host: xxx, port: 25;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Please provide me some hint, what I am doing wrong in above case.
You can try to do simply following and it should work for you
grails {
mail {
host = "xxx"
port = 25
username = "xxx"
props = ["mail.smtp.auth":"false",
"mail.smtp.socketFactory.port":"25",
"mail.smtp.starttls.enable": "true"]
}
}

Umbraco mvc Please help me with the HandleForgottenPassword

I have been ask this question for few days but no answer, i am very new to Umbraco and junior of programming.i am working on trying to get admin user to reset password when they are forget their password and sent them an email to reset their password, after they
reset they password they will get a new password to login when they
login they we will force them to change password, so for now i am
struggle on the HandleForgottenPassword, getting
Object reference not set to an instance of an object. on the yellow line,
enter code here
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult HandleForgottenPassword(ForgottenPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView("ForgottenPassword", model);
}
//Find the member with the email address
var name =Member.GetMemberFromLoginName(model.LoginName);
var findMember = Member.GetMemberFromEmail(model.EmailAddress);
if (findMember != null)
{
//We found the member with that email
//Set expiry date to
DateTime expiryTime = DateTime.Now.AddMinutes(15);
//Lets update resetGUID property
// findMember.getProperty("resetGUID").Value = expiryTime.ToString("ddMMyyyyHHmmssFFFF");
//Save the member with the up[dated property value
findMember.Save();
//Send user an email to reset password with GUID in it
EmailHelper email = new EmailHelper();
email.SendResetPasswordEmail(findMember.Email, expiryTime.ToString("ddMMyyyyHHmmssFFFF"));
}
else
{
ModelState.AddModelError("ForgottenPasswordForm.", "No member found");
return PartialView("ForgottenPassword", model);
}
return PartialView("ForgottenPassword", model);
}
please help with sending email ( using EmailHelper from the package)
private const string SendGridUsername = "sendGridUsername";
private const string SendGridPassword = "sendGridPassword";
private const string EmailFromAddress = "you#yoursite.com";
public void SendResetPasswordEmail(string memberEmail, string resetGUID)
{
//Send a reset email to member
// Create the email object first, then add the properties.
var myMessage = SendGrid.GetInstance();
// Add the message properties.
myMessage.From = new MailAddress(EmailFromAddress);
//Send to the member's email address
myMessage.AddTo(memberEmail);
//Subject
myMessage.Subject = "Umb Jobs - Reset Your Password";
//Reset link
string baseURL = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty);
var resetURL = baseURL + "/reset-password?resetGUID=" + resetGUID;
//HTML Message
myMessage.Html = string.Format(
"<h3>Reset Your Password</h3>" +
"<p>You have requested to reset your password<br/>" +
"If you have not requested to reste your password, simply ignore this email and delete it</p>" +
"<p><a href='{0}'>Reset your password</a></p>", resetURL);
//PlainText Message
myMessage.Text = string.Format(
"Reset your password" + Environment.NewLine +
"You have requested to reset your password" + Environment.NewLine +
"If you have not requested to reste your password, simply ignore this email and delete it" +
Environment.NewLine + Environment.NewLine +
"Reset your password: {0}",
resetURL);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(SendGridUsername, SendGridPassword);
// Create an SMTP transport for sending email.
var transportSMTP = SMTP.GetInstance(credentials);
// Send the email.
transportSMTP.Deliver(myMessage);
}
when i try to sending the email i got this erro
Unable to read data from the transport connection: net_io_connectionclosed.
here is my *web.config *
<system.net>
<mailSettings>
<smtp>
<network host="127.0.0.1" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
Thank you in advance. MC
If you are on a residential internet connection quite often your ISP will block outgoing email sends by blocking all outbound connections to port 25. This is quite common in the US. Try connecting to a local email server over TCP/IP, or to one on your own internal network.

AWS SES, Mail plugin and Grails configuration

I'm trying to set up the Mail plugin with my SES credentials, but I am obviously missing something because I keep getting this error:
Class: javax.mail.NoSuchProviderException
Message: No provider for aws
I've added the following to my Config.groovy:
grails {
mail {
host = "email-smtp.us-east-1.amazonaws.com"
port = 465
username = "XXXXXXXXX"
password = "YYYYYYYYY"
props = [
'mail.transport.protocol': 'aws',
'mail.aws.class': 'com.amazonaws.services.simpleemail.AWSJavaMailTransport',
'mail.aws.user': 'WWWWWWWWWWWW',
'mail.aws.password': 'ZZZZZZZZZZZ'
]
}
}
I've been looking through all the possible tutorials, half of them were from the time SES didn't support SMTP, thats why I have the class reference from the maven repo.
Does anyone know how I can configure this?
This is what I have been using successfully -
grails {
mail {
host = "email-smtp.us-east-1.amazonaws.com"
port = 587
username = "smtp user name"
password = "smtp password"
props = ["mail.smtp.starttls.enable":"true",
"mail.smtp.port":"587"]
}
}
Let me know if the above works

asp.net mvc send email error: unable to send an email

I have mvc web app sending an email when new user gets created with following code:
private static void SendMail(User user)
{
string ActivationLink = "http://localhost/Account/Activate/" +
user.UserName + "/" + user.NewEmailKey;
var message = new MailMessage("ashu#gmail.com", user.Email)
{
Subject = "Activate your account",
Body = ActivationLink
};
var client = new SmtpClient("localhost");
client.UseDefaultCredentials = false;
client.Send(message);
}
What's wrong with my code please tell me.
ERROR : Failure sending mail. {"Unable to connect to the remote server"}
Smtp configuration :
Here are the likely causes of this error:
1 You are not supplying the correct authentication details
2 The port is blocked, for example by a firewall
In your example, I notice you are not specifying the port when you create your SmtpClient - it may help to specify it.
Gmail opens in port 587, and u need to enable ssl.
Try following code.
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(<fromAddress>, <fromPassword>)
};
using (var message = new MailMessage(<fromAddress>, <toAddress>)
{
Subject = <subject>,
Body = <body>
})
{
smtp.Send(message);
}

Resources