Hello,
I am in need of a expert that can help me. The following problem is eating me from the inside. I am trying to build an automailer. next to it being it a automailer it has to be able to send scheduled email.
please help
package main
import (
“encoding/json”
“flag”
“fmt”
“io/ioutil”
“os”
“time”
"gopkg.in/gomail.v2"
)
type Config struct {
SMTPServer string json:"smtp_server"
SMTPPort int json:"smtp_port"
SMTPUser string json:"smtp_user"
SMTPPassword string json:"smtp_password"
EmailFrom string json:"email_from"
EmailTo string json:"email_to"
}
func main() {
// Parse command-line arguments
scheduleDate := flag.String(“date”, “”, “Date for sending the email (YYYY-MM-DD)”)
scheduleTime := flag.String(“time”, “”, “Time for sending the email (HH:MM)”)
flag.Parse()
// Verify command-line arguments
if *scheduleDate == "" || *scheduleTime == "" {
fmt.Println("Please provide both the date and time for scheduling the email.")
return
}
// Open the JSON file
file, err := os.Open("config.json")
if err != nil {
panic(err)
}
defer file.Close()
// Read the JSON file
bytes, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
// Decode the JSON data into the Config struct
var config Config
err = json.Unmarshal(bytes, &config)
if err != nil {
panic(err)
}
// Create a new email message
m := gomail.NewMessage()
// Set the details of the email
m.SetHeader("From", config.EmailFrom)
m.SetHeader("To", config.EmailTo)
m.SetHeader("Subject", "Test Mail from Go")
// Set the body of the email
m.SetBody("text/html", "This is the content of the email.")
// Create a new dialer for the mail server
d := gomail.NewDialer(config.SMTPServer, config.SMTPPort, config.SMTPUser, config.SMTPPassword)
// Parse the provided date and time strings
layout := "2006-01-02 15:04" // Format for parsing date and time
scheduleDateTime := fmt.Sprintf("%s %s", *scheduleDate, *scheduleTime)
scheduledTime, err := time.Parse(layout, scheduleDateTime)
if err != nil {
fmt.Println("Invalid date or time format. Please provide the date in the format 'YYYY-MM-DD' and the time in the format 'HH:MM'.")
return
}
// Calculate the duration until the scheduled time
duration := scheduledTime.Sub(time.Now())
// Check if the scheduled time has already passed
if duration < 0 {
fmt.Println("The specified scheduled time has already passed.")
return
}
// Print scheduled time for debugging
fmt.Println("Scheduled time:", scheduledTime)
// Schedule the email to be sent at the specified time
timer := time.NewTimer(duration)
// Wait for the timer to expire
<-timer.C
// Print current time for debugging
fmt.Println("Current time:", time.Now())
// ...
// Send the email with the dialer
if err := d.DialAndSend(m); err != nil {
fmt.Println("Failed to send the email:", err)
os.Exit(1)
}
// Print a message indicating that the email has been sent
fmt.Println("The email has been sent!")
}