Just sharing email validation code
func ValidateEmail(email string) (bool, error) {
syntaxPattern := `^[a-zA-Z0-9.!#$%&'*+/=?^_\x60{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$`
matched, _ := regexp.MatchString(syntaxPattern, email)
if !matched {
return false, fmt.Errorf("invalid email syntax")
}
// Extract user and host parts
parts := strings.Split(email, "@")
if len(parts) != 2 {
return false, fmt.Errorf("invalid email format")
}
host := parts[1]
// Lookup MX records for the host
mxRecords, err := net.LookupMX(host)
if err != nil || len(mxRecords) == 0 {
return false, fmt.Errorf("no MX records found for domain")
}
// Select one MX record (simulates choosing a random one)
mxHost := mxRecords[0].Host
// Establish an SMTP connection
conn, err := net.DialTimeout("tcp", mxHost+":25", 60*time.Second)
if err != nil {
return false, fmt.Errorf("failed to connect to mail server: %v", err)
}
defer conn.Close()
// SMTP conversation
commands := []string{
"HELO example.com\r\n",
"MAIL FROM:<[email protected]>\r\n",
fmt.Sprintf("RCPT TO:<%s>\r\n", email),
"QUIT\r\n",
}
// Send SMTP commands
reader := bufio.NewReader(conn)
for _, cmd := range commands {
fmt.Println(cmd)
_, err := conn.Write([]byte(cmd))
if err != nil {
return false, fmt.Errorf("failed to send SMTP command: %v", err)
}
// Read server response
response, _ := reader.ReadString('\n')
fmt.Println(response)
if strings.HasPrefix(response, "550") {
return false, fmt.Errorf("email does not exist on server")
}
}
return true, nil
}
It works on servers but not on local computer I don't know why