#14: First effort of adding more example code

This commit is contained in:
Winni Neessen 2022-06-03 13:33:57 +02:00
parent 97e1386e36
commit 345ad6cceb
Signed by: wneessen
GPG key ID: 385AC9889632126E

View file

@ -1,9 +1,12 @@
package mail_test
import (
"context"
"fmt"
"github.com/wneessen/go-mail"
"os"
"text/template"
"time"
)
// Code example for the NewClient method
@ -61,3 +64,73 @@ func ExampleClient_DialAndSend() {
os.Exit(1)
}
}
// This code example shows how to use Msg.SetBodyString to set a string as message body with
// different content types
func ExampleMsg_SetBodyString_differentTypes() {
m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is a mail body that with content type: text/plain")
m.SetBodyString(mail.TypeTextHTML, "<p>This is a mail body that with content type: text/html</p>")
}
// This code example shows how to use Msg.SetBodyString to set a string as message body a PartOption
// to override the default encoding
func ExampleMsg_SetBodyString_withPartOption() {
m := mail.NewMsg(mail.WithEncoding(mail.EncodingB64))
m.SetBodyString(mail.TypeTextPlain, "This is a mail body that with content type: text/plain",
mail.WithPartEncoding(mail.EncodingQP))
}
// This code example shows how to use a text/template as message Body.
// Msg.SetBodyHTMLTemplate works anolog to this just with html/template instead
func ExampleMsg_SetBodyTextTemplate() {
type MyStruct struct {
Placeholder string
}
data := MyStruct{Placeholder: "Teststring"}
tpl, err := template.New("test").Parse("This is a {{.Placeholder}}")
if err != nil {
panic(err)
}
m := mail.NewMsg()
if err := m.SetBodyTextTemplate(tpl, data); err != nil {
panic(err)
}
}
// This code example shows how to utilize the Msg.WriteToSendmail method to send generated mails
// using a local sendmail installation
func ExampleMsg_WriteToSendmail() {
m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is the mail body string")
if err := m.FromFormat("Toni Tester", "toni.tester@example.com"); err != nil {
panic(err)
}
if err := m.To("gandalf.tester@example.com"); err != nil {
panic(err)
}
if err := m.WriteToSendmail(); err != nil {
panic(err)
}
}
// This code example shows how to send generated mails using a custom context and sendmail-compatbile command
// using the Msg.WriteToSendmailWithContext method
func ExampleMsg_WriteToSendmailWithContext() {
sendmailPath := "/opt/sendmail/sbin/sendmail"
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
m := mail.NewMsg()
m.SetBodyString(mail.TypeTextPlain, "This is the mail body string")
if err := m.FromFormat("Toni Tester", "toni.tester@example.com"); err != nil {
panic(err)
}
if err := m.To("gandalf.tester@example.com"); err != nil {
panic(err)
}
if err := m.WriteToSendmailWithContext(ctx, sendmailPath); err != nil {
panic(err)
}
}