github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/experimental/plugin_sendmail.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  	"os/exec"
     7  	"runtime"
     8  
     9  	c "github.com/Azareal/Gosora/common"
    10  )
    11  
    12  /*
    13  	Sending emails in a way you really shouldn't be sending them.
    14  	This method doesn't require a SMTP server, but has higher chances of an email being rejected or being seen as spam. Use at your own risk. Only for Linux as Windows doesn't have Sendmail.
    15  */
    16  func init() {
    17  	// Don't bother registering this plugin on platforms other than Linux
    18  	if runtime.GOOS != "linux" {
    19  		return
    20  	}
    21  	c.Plugins.Add(&c.Plugin{UName: "sendmail", Name: "Sendmail", Author: "Azareal", URL: "http://github.com/Azareal", Tag: "Linux Only", Init: initSendmail, Activate: activateSendmail, Deactivate: deactivateSendmail})
    22  }
    23  
    24  func initSendmail(plugin *c.Plugin) error {
    25  	plugin.AddHook("email_send_intercept", sendSendmail)
    26  	return nil
    27  }
    28  
    29  // /usr/sbin/sendmail is only available on Linux
    30  func activateSendmail(plugin *c.Plugin) error {
    31  	if !c.Site.EnableEmails {
    32  		return errors.New("You have emails disabled in your configuration file")
    33  	}
    34  	if runtime.GOOS != "linux" {
    35  		return errors.New("This plugin only supports Linux")
    36  	}
    37  	return nil
    38  }
    39  
    40  func deactivateSendmail(plugin *c.Plugin) {
    41  	plugin.RemoveHook("email_send_intercept", sendSendmail)
    42  }
    43  
    44  func sendSendmail(data ...interface{}) interface{} {
    45  	to := data[0].(string)
    46  	subject := data[1].(string)
    47  	body := data[2].(string)
    48  
    49  	msg := "From: " + c.Site.Email + "\n"
    50  	msg += "To: " + to + "\n"
    51  	msg += "Subject: " + subject + "\n\n"
    52  	msg += body + "\n"
    53  
    54  	sendmail := exec.Command("/usr/sbin/sendmail", "-t", "-i")
    55  	stdin, err := sendmail.StdinPipe()
    56  	if err != nil {
    57  		return err // Possibly disable the plugin and show an error to the admin on the dashboard? Plugin log file?
    58  	}
    59  
    60  	err = sendmail.Start()
    61  	if err != nil {
    62  		return err
    63  	}
    64  	io.WriteString(stdin, msg)
    65  
    66  	err = stdin.Close()
    67  	if err != nil {
    68  		return err
    69  	}
    70  	return sendmail.Wait()
    71  }