This commit is contained in:
Star 2025-05-01 16:32:41 +08:00
commit b7c7e6c062
6 changed files with 312 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
.*
!.gitignore
go.sum
node_modules
package.json
env.yml

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

34
go.mod Normal file
View File

@ -0,0 +1,34 @@
module apigo.cc/gojs/mail
go 1.18
require (
apigo.cc/gojs v0.0.12
apigo.cc/gojs/console v0.0.2
apigo.cc/gojs/redis v0.0.2
github.com/ssgo/u v1.7.13
)
require (
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/emersion/go-imap v1.2.1 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/gomodule/redigo v1.9.2 // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/ssgo/config v1.7.9 // indirect
github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/redis v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect
github.com/ssgo/tool v0.4.28 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
golang.org/x/net v0.32.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

233
plugin.go Normal file
View File

@ -0,0 +1,233 @@
package plugin
import (
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"net/smtp"
"strings"
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
"github.com/jaytaylor/html2text"
"github.com/ssgo/config"
"github.com/ssgo/u"
"gopkg.in/gomail.v2"
)
const pluginName = "mail"
var defaultObjectName = "default"
var defaultObject = &DefaultObject{}
var confAes *u.Aes = u.NewAes([]byte("?GQ$0K0GgLdO=f+~L68PLm$uhKr4'=tV"), []byte("VFs7@sK61cj^f?HZ"))
var objects = make(map[string]*Object)
func init() {
tsCode := gojs.MakeTSCode(defaultObject)
gojs.Register("apigo.cc/gojs/"+pluginName, gojs.Module{
ObjectMaker: func(vm *goja.Runtime) gojs.Map {
configs := make(map[string]*Config)
config.LoadConfig(pluginName, &configs)
for name, object := range configs {
objects[name] = defaultObject.New(*object)
}
defaultObject.Object = defaultObject.GetInstance("default")
return gojs.ToMap(defaultObject)
},
TsCode: tsCode,
Desc: "mail api by github.com/ssgo/mail",
SetSSKey: func(key, iv []byte) {
confAes = u.NewAes(key, iv)
},
})
}
type DefaultObject struct {
*Object
}
func (obj *DefaultObject) GetInstance(name string) *Object {
if o, ok := objects[name]; ok {
return o
} else {
return obj.Object
}
}
func (obj *DefaultObject) New(conf Config) *Object {
a := strings.SplitN(conf.Username, "@", 2)
if len(a) == 2 {
if conf.SmtpHost == "" {
conf.SmtpHost = "smtp." + a[1]
}
if conf.SmtpPort == 0 {
conf.SmtpPort = 465
}
if conf.ImapHost == "" {
conf.ImapHost = "imap." + a[1]
}
if conf.ImapPort == 0 {
conf.ImapPort = 993
}
}
fmt.Println(u.BMagenta(u.JsonP(conf)), 111)
return &Object{
smtpHost: conf.SmtpHost,
smtpPort: conf.SmtpPort,
imapHost: conf.ImapHost,
imapPort: conf.ImapPort,
username: conf.Username,
password: confAes.DecryptUrlBase64ToString(conf.Password),
senderName: conf.SenderName,
}
}
type Config struct {
SmtpHost string
SmtpPort int
ImapHost string
ImapPort int
Username string
Password string
SenderName string
}
type Object struct {
smtpHost string
smtpPort int
imapHost string
imapPort int
username string
password string
senderName string
}
type Attachment struct {
Path string
Name string
Data string
ContentType string
}
type SendOption struct {
Cc []string
Bcc []string
Html bool
Attachments []Attachment
Embeds []Attachment
}
func (obj *Object) Send(vm *goja.Runtime, to []string, subject, content string, option *SendOption) error {
logger := gojs.GetLogger(vm)
msg := gomail.NewMessage()
if obj.senderName != "" {
msg.SetHeader("From", msg.FormatAddress(obj.username, obj.senderName))
} else {
msg.SetHeader("From", obj.username)
}
msg.SetHeader("To", to...)
msg.SetHeader("Subject", subject)
useHtml := false
if option != nil {
if len(option.Cc) > 0 {
msg.SetHeader("Cc", option.Cc...)
}
if len(option.Bcc) > 0 {
msg.SetHeader("Bcc", option.Bcc...)
}
if len(option.Attachments) > 0 {
for _, attachment := range option.Attachments {
if attachment.Path != "" {
if u.FileExists(attachment.Path) {
msg.Attach(attachment.Path)
} else {
logger.Error("mail attachment file not exists", "filename", attachment.Path, "to", to, "subject", subject)
}
} else if attachment.Data != "" {
if attachment.Name == "" {
attachment.Name = "attachment"
}
if attachment.ContentType == "" {
attachment.ContentType = "text/plain"
}
buf, err := base64.StdEncoding.DecodeString(attachment.Data)
if err != nil {
buf = []byte(attachment.Data)
}
msg.Attach(attachment.Name, gomail.SetCopyFunc(func(w io.Writer) error {
_, err := w.Write(buf)
return err
}), gomail.SetHeader(map[string][]string{
"Content-Type": {attachment.ContentType},
}))
}
}
}
if len(option.Embeds) > 0 {
for _, attachment := range option.Embeds {
if attachment.Path != "" {
if u.FileExists(attachment.Path) {
msg.Attach(attachment.Path)
} else {
logger.Error("mail embed file not exists", "filename", attachment.Path, "to", to, "subject", subject)
}
} else if attachment.Data != "" {
if attachment.Name == "" {
attachment.Name = "image"
}
if attachment.ContentType == "" {
attachment.ContentType = "image/png"
}
buf, err := base64.StdEncoding.DecodeString(attachment.Data)
if err != nil {
buf = []byte(attachment.Data)
}
msg.Embed(attachment.Name, gomail.SetCopyFunc(func(w io.Writer) error {
_, err := w.Write(buf)
return err
}), gomail.SetHeader(map[string][]string{
"Content-Type": {attachment.ContentType},
"Content-ID": {"<" + attachment.Name + ">"},
}))
}
}
}
useHtml = option.Html
}
if useHtml {
msg.SetBody("text/html", content)
textContent, err := html2text.FromString(content, html2text.Options{TextOnly: true, PrettyTables: true})
if err != nil {
logger.Error("convert html to text failed", "err", err, "to", to, "subject", subject, "content", content)
textContent = content
}
msg.AddAlternative("text/plain", textContent)
} else {
msg.SetBody("text/plain", content)
}
conn := gomail.NewDialer(obj.smtpHost, obj.smtpPort, obj.username, obj.password)
switch obj.smtpPort {
case 465:
conn.SSL = true
case 587:
conn.TLSConfig = &tls.Config{
ServerName: obj.smtpHost,
InsecureSkipVerify: false,
}
}
conn.Auth = smtp.PlainAuth("", obj.username, obj.password, obj.smtpHost)
err := conn.DialAndSend(msg)
if err != nil {
logger.Error("send mail failed", "err", err.Error(), "to", to, "subject", "from", obj.username, subject, "content", content)
} else {
logger.Info("send mail success", "to", to, "from", obj.username, "subject", subject)
}
return err
}

21
plugin_test.go Normal file
View File

@ -0,0 +1,21 @@
package plugin_test
import (
"fmt"
"testing"
"apigo.cc/gojs"
"github.com/ssgo/u"
)
func TestPlugin(t *testing.T) {
gojs.ExportForDev()
r, err := gojs.RunFile("plugin_test.js")
if err != nil {
t.Fatal(err)
} else if r != true {
t.Fatal(r)
} else {
fmt.Println(u.BGreen("test succeess"))
}
}

9
plugin_test.js Normal file
View File

@ -0,0 +1,9 @@
import mail from 'apigo.cc/gojs/mail'
mail.send(['star3s@126.com'], '测试邮件', '这是一个测试邮件<br/><img src="cid:1.png"/> !!', {
cc: ['isstar3s@126.com'],
html: true,
embeds: [{ name: '1.png', data: 'iVBORw0KGgoAAAANSUhEUgAAABEAAAATCAMAAABBexbDAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA2LjAuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Chle4QcAAABjUExURaOju6yiu6ajtqKlt7ijttenuaCmvcipuOezvKStwbW2yqSgudSsuNyyuaSpvZeasua3uqWjtcSwv9XR6MS80ei0ys3H3audsLKswruqu8qjvOKrxOKtudOwveTe8+i3xMXC2TWaOysAAADFSURBVBjTRc7tssMQEAZgqW8VFBVEmtz/VZ5dOZ2+M368j92BEMzjdecBmSAI/dEEIegdKM8bxLeT5xStqXOUign/4pyDQxYMitMG4xYgtoFooU0q2VQYYIyhmHx9PgmIMSk7bl2poMTWmOQcpJqSUrpyjBJg4AdqLqVk6NbyoUCWWluMh4X7NQSFD7YJYwylQljJwnrH+VVhDisJY51z2A+wsB4Sfth757s6T5i30DdPON/39/s85/3mvSfYIYdsL+ze/wG5Qw7KZj0DQwAAAABJRU5ErkJggg==' }],
})
return true