To send emails using the Gmail API with an API key, you need to set up an API key in the Google Cloud Console.
- Go to Google Cloud Console.
- Create a new project.
- In the Google Cloud Console, navigate to "APIs & Services" > "Library".
- Search for "Gmail API" and enable it for your project.
- Go to "APIs & Services" > "Credentials".
- Click "Create credentials" and select "API Key".
- Copy the generated API key and store it securely.
// API key (in production, retrieve from a secure file or secret manager)
apiKey := "your-api-key"
// User for whom the email is being sent
user := "me"
// Initialize the GmailEmailSender
emailSender, err := gmail.NewGmailEmailSenderAPIKey(apiKey, user)
if err != nil {
log.Fatalf("Failed to create GmailEmailSender: %v", err)
}
// Read attachment content
attachmentContent, err := os.ReadFile("path/to/attachment.jpg")
if err != nil {
log.Fatalf("Failed to read attachment: %v", err)
}
// Define email message using an alias email address
message := gomail.NewEmailMessage("your-email_or_alias@example.com",[]string{"recipient@example.com"}, "Test Email with attachment", "This is the plain text part of the email.").
SetHTML("<p>This is the <b>HTML</b> part of the <i>email</i>.</p>").AddAttachments(*gomail.NewAttachment("attachment.jpg", attachmentContent))
// Send email
if err := emailSender.SendEmail(message); err != nil {
log.Fatalf("Failed to send email: %v", err)
}
fmt.Println("Email sent successfully")