-1

Here are the screenshots and code attached Code:

exports.forgotPassword = async function(req, res, next) {

     //Check if user exists
     const user = await User.findOne({ email: req.body.email })
     if (!user) {
         return next(new AppError('There is no user with this email address', 404))
     }

     //Generate the random reset token 
     const resetToken = user.createPasswordResetToken()
     await user.save({ validateBeforeSave: false });

     //send it to user's mail
     const resetURL = `${req.protocol}://${req.get('host')}/api/users/resetPassword/${resetToken}`;
     const message = `Forgot your Password? Submit a patch request with your password and confirm password to ${resetURL}`

     try {

         await sendEmail({
             email: user.email,
             subject: 'Your password reset token(valid for 10 min)'
         })

         res.status(200).json({
             status: 'success',
             message: 'Token sent to Email'
         })
     } catch (err) {
         user.passwordResetToken = undefined;
         user.passwordResetExpires = undefined;
         await user.save({ validateBeforeSave: false });
         return next(new AppError('There was an error sending the email. Please try again later!'), 500);
     }
 }

Error Message :

Error: There was an error sending the email. Please try again later!
    at exports.forgotPassword (D:\FYP\controllers\authController.js:94:22)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Error: getaddrinfo ENOTFOUND smtp.mailtrap.io;
    at GetAddrInfoReqWrap.onlookup [as oncomplete] 

(node:dns:71:26) {
  errno: -3008,
  code: 'EDNS',
  syscall: 'getaddrinfo',
  hostname: 'smtp.mailtrap.io;',
  command: 'CONN'
}
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • It seems like something (probably `await sendEmail`) in the `try` block throws an exception. It would be helpful to log `err`. – jabaa Feb 23 '22 at 16:02
  • Yes I logged the error seems like Im having issue with mailtrap which im using with nodemailer Error: getaddrinfo ENOTFOUND smtp.mailtrap.io; at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) { errno: -3008, code: 'EDNS', syscall: 'getaddrinfo', hostname: 'smtp.mailtrap.io;', command: 'CONN' } – hamza awan Feb 23 '22 at 16:12
  • 1
    Why do you have a semicolon in the hostname? Is this a typo? – jabaa Feb 23 '22 at 16:19
  • Yes it was a typo but I got my issue. The problem was the mailtrap which im using as a service in nodemailer, I just changed the port from 25 to 2525 and renamed password key to "pass" and it worked https://stackoverflow.com/questions/48854066/missing-credentials-for-plain-nodemailer this thread helped me – hamza awan Feb 23 '22 at 16:50
  • That's not the cause of `getaddrinfo ENOTFOUND`. The cause of this error is a wrong hostname. The wrong port was an additional error, but it wasn't relevant for this error message. – jabaa Feb 23 '22 at 16:51
  • Yes Yes got it Thanks :) – hamza awan Feb 23 '22 at 16:57

1 Answers1

-2

look at my code it used express.js with typescript use ndoemailer to send email

https://nodemailer.com/about/

  public async forgot(entity: AuthEntity): Promise<void> {
    if (isEmpty(entity)) throw new HttpException(StatusCodes.BAD_REQUEST, i18n.t("api.commons.reject"));


    let findUser: IUser;

  
    if (entity.email !== undefined) {
      findUser = await this.userModel.findOne({ email: entity.email });
      if (!findUser) {
        // @ts-ignore
        await ipActivityModel.storeIp(false, "forgot", entity);
        throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.youAreNotEmail"));
      }
      await this.sendForgotEmail(findUser.email, entity.resetToken);

    }
   
    
    
  }


  public async sendForgotEmail(email: string, hash: string): Promise<void> {
    const transporter = nodemailer.createTransport({
      host: config.get("email.host"),
      port: config.get("email.port"),
      secure: config.get("email.secure"), // true for 465, false for other ports
      auth: config.get("email.auth")
    });
    const mailContext = {
      siteAddress: config.get("siteAddress"),
      emailForgotTitle: i18n.t("auth.emailForgotTitle"),
      emailForgotGuide: i18n.t("auth.emailForgotGuide"),
      emailActivateHash: i18n.t("auth.emailActivateHash"),
      hash: hash,
      emailForgotVisit: i18n.t("auth.emailForgotVisit"),
      emailActivateIgnore: i18n.t("auth.emailActivateIgnore"),
      emailForgotResetFrom: i18n.t("auth.emailForgotResetFrom")
    };
    const template = await ejs.renderFile("./dist/modules/auth/views/forgot.html", mailContext);

    const mailOptions = {
      from: config.get("email.fromEmail"),
      to: email,
      subject: config.get("siteAddress") + " (" + i18n.t("api.events.emailForgot") + ")",
      html: template

    };
    let isSend = await transporter.sendMail(mailOptions);
    if (!isSend.messageId) {
      throw new HttpException(StatusCodes.CONFLICT, i18n.t("auth.emailSendErrorForgot"));

    }
  }


paliz
  • 347
  • 2
  • 5
  • i use nodemailer for sending email – paliz Feb 23 '22 at 18:27
  • _"Look at my code"_ answers are not useful. What was the problem? How did you solve it? How could someone avoid the same problem in the future? Why would you change most of the code to fix two simple typos? – jabaa Feb 23 '22 at 18:30
  • my friend its working i tested it on live host and it was part of my project – paliz Feb 23 '22 at 18:38
  • Your code could be great, but your answer isn't useful. It doesn't help the asker and other visitors with a similar error message. – jabaa Feb 23 '22 at 18:42
  • the code its huge not suit for here ,i grab part of it to help folks – paliz Feb 23 '22 at 18:43
  • Stack Overflow isn't a code publishing website. There is a question, and your answer doesn't address the question in any way. You didn't describe or explain the problem. You didn't provide a solution for the problem. You can post your code on GitHub or GitLab. – jabaa Feb 23 '22 at 18:44
  • i know best way write codes it matter too and also and i try help ppl – paliz Feb 23 '22 at 18:46
  • Posting unrelated code is the opposite of helping people. It's confusing people. People come here to find a solution to their problem, wasting their time reading your answer to find out that it doesn't address the problem. – jabaa Feb 23 '22 at 18:49
  • my codes are clean and programmer can read it easily – paliz Feb 23 '22 at 18:50
  • But ut doesn't solve the problem in the question. – jabaa Feb 23 '22 at 18:50
  • oky i convence to answer as sample as possible – paliz Feb 23 '22 at 18:51
  • you are wrong it s show way how to send email – paliz Feb 23 '22 at 18:54
  • The asker has a specific problem with a specific error message. It's not an option to change the email service provide. Your code doesn't fix the problem. They already know, how to send email. – jabaa Feb 23 '22 at 18:56
  • my friend i give up :-))))) – paliz Feb 23 '22 at 19:26