Failed to start TLS: 421 Local Error, closing transmission channel

45 Views Asked by At

Title: Error: Failed to start TLS when sending OTP email using Mailtrap in Go

Description:

I'm working on implementing OTP email verification for user sign-in in my Go application using Mailtrap as the SMTP server. However, when attempting to send the OTP email, I encounter the following error:

Generated OTP: 570528
Sending OTP email to: [email protected]
Error sending OTP email: failed to start TLS: 421 Local Error, closing transmission channel

Here's the relevant code snippet:

// Send OTP email
err := sendOTPEmail(user.Email, otp)
if err != nil {
    fmt.Println("Error sending OTP email:", err)
    c.Status(http.StatusInternalServerError)
    return c.JSON(fiber.Map{
        "error": "Error sending OTP",
    })
}

And here's the sendOTPEmail function responsible for sending the email:

func sendOTPEmail(email, otp string) error {
    // Connect to the SMTP server
    client, err := smtp.Dial(smtpHost + ":" + strconv.Itoa(smtpPort))
    if err != nil {
        return fmt.Errorf("failed to connect to SMTP server: %v", err)
    }
    defer client.Close()

    // Start TLS encryption
    if err := client.StartTLS(nil); err != nil {
        return fmt.Errorf("failed to start TLS: %v", err)
    }

    // Authentication
    auth := smtp.PlainAuth("", smtpUser, smtpPassword, smtpHost)
    if err := client.Auth(auth); err != nil {
        return fmt.Errorf("authentication failed: %v", err)
    }

    // Compose the email message
    subject := "Your OTP for sign-in"
    body := fmt.Sprintf("Your OTP (One-Time Password) for sign-in is: %s", otp)
    msg := []byte("To: " + email + "\r\n" +
        "Subject: " + subject + "\r\n" +
        "\r\n" +
        body)

    // Send the email
    if err := client.Mail(smtpUser); err != nil {
        return fmt.Errorf("failed to send MAIL command: %v", err)
    }
    if err := client.Rcpt(email); err != nil {
        return fmt.Errorf("failed to send RCPT command: %v", err)
    }
    w, err := client.Data()
    if err != nil {
        return fmt.Errorf("failed to open data writer: %v", err)
    }
    defer w.Close()

    _, err = w.Write(msg)
    if err != nil {
        return fmt.Errorf("failed to write email body: %v", err)
    }

    return nil
}

I've ensured that the SMTP credentials (smtpUser and smtpPassword) are correct, and I'm using the correct SMTP host and port provided by Mailtrap. However, I'm still encountering this TLS-related error.

What could be causing this issue, and how can I resolve it?

0

There are 0 best solutions below