-
-
Notifications
You must be signed in to change notification settings - Fork 81
SOCKS5 Proxy Example
While go-mail by default does not implement SOCKS5 Proxy support, it provides support for custom DialContext
functions. This can be used in combination with golang.org/x/net/proxy to implement a custom dial context
with SOCKS5 support.
This example code shows how this could look like.
Test on play.go.dev
package main
import (
"context"
"log"
"net"
"github.com/wneessen/go-mail"
"golang.org/x/net/proxy"
)
func main() {
message := mail.NewMsg()
if err := message.From("[email protected]"); err != nil {
log.Fatalf("failed to set From address: %s", err)
}
if err := message.To("[email protected]"); err != nil {
log.Fatalf("failed to set To address: %s", err)
}
message.Subject("This is my first mail with go-mail!")
message.SetBodyString(mail.TypeTextPlain, "Do you like this mail? I certainly do!")
dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:1080", nil, proxy.Direct)
if err != nil {
log.Fatalf("failed to create SOCKS5 proxy: %s", err)
}
client, err := mail.NewClient("smtp.example.com", mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover),
mail.WithUsername("my_username"), mail.WithPassword("extremely_secret_pass"),
mail.WithDialContextFunc(func(_ context.Context, network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
}),
)
if err != nil {
log.Fatalf("failed to create mail client: %s", err)
}
if err := client.DialAndSend(message); err != nil {
log.Fatalf("failed to send mail: %s", err)
}
}Most of the code is explained in the Simple-Mailer-Example. Check out that page for detailed explanations.
The only difference is, that before initializing the Client, we create a new SOCKS5 dialer using
the golang.org/x/net/proxy package. This dial is then used in our custom DialContextFunc which
we add to the client initialization using the mail.WithDialContextFunc option. Now, once the client
tries to connect to the SMTP server, it will tunnel the traffic through the SOCKS5 proxy instead.
Socials: go-mail on Mastodon | #go-mail on Discord | #go-mail on Slack