DEV Community

oritsegbubemi
oritsegbubemi

Posted on

How to send email with Go and MailTrap

#go

Sending emails is a common requirement in many applications. Whether it's for account verification, password reset, or notifications, integrating email functionality can enhance the user experience. In this post, we'll walk through the steps to send emails using Go, leveraging the gomail package.

Prerequisites
Ensure you have the following dependencies in your go.mod file:

require (
github.com/joho/godotenv v1.4.0
gopkg.in/gomail.v2 v2.0.0-20180604020328-0353e461b93c
)

Step 1: Create a .env file with the following content

MAILTRAP_HOST=smtp.mailtrap.io
MAILTRAP_PORT=2525
MAILTRAP_USER=your_mailtrap_user
MAILTRAP_PASS=your_mailtrap_password
SENDER=your_sender_email@example.com

Step 2: Create the SendMail Function
Now, we will create the SendMail function to handle email sending. This function will read the configuration from the environment variables and use the gomail package to send the email.

Image description

Step 3: Integrate Email Sending in Your Application
Let's say you have a user verification process where you need to send an OTP (One-Time Password) to the user's email. Here's an example of how you can integrate the SendMail function into your application:

Image description

Step 4: Create an Endpoint to Trigger Email Sending
Finally, you need an endpoint to trigger the email sending. Here is an example using the Gin framework:

Image description

Image description

In your server setup, register this endpoint:

Image description

With this setup, you can now send emails from your Go application using the SendMail function. This method ensures your credentials are secure and that your email sending logic is cleanly separated from the rest of your application.

Feel free to customize the code and the explanations according to your specific requirements and style preferences!

Link to the Full code
https://github.com/gbubemi22/goSetup

Top comments (1)

Collapse
 
der_gopher profile image
Alex Pliutau

Great write-up, we have a bunch of articles on Go in our Newsletter, check it out - packagemain.tech