duanlei0282 2013-12-05 02:48
浏览 12
已采纳

联系表单邮件处理程序示例以继续进行Appengine

To my surprise I did not find a contact form mail handler example for go? I don't feel like making a wheel today, are there examples available?

EDIT: (cut and paste answer)

package bin

import (
    "fmt"
    "net/http"
    netMail "net/mail"
    "appengine"
    "appengine/mail"
)

func contact(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    name := r.FormValue("name")
    email := r.FormValue("email")
    subject := r.FormValue("subject")
    message := r.FormValue("message")
    msg := &mail.Message{
            Sender:  name + " <...@yourappid.appspotmail.com>",
            To:      []string{"...@..."},
            ReplyTo: email,
            Subject: subject,
            Body:    message,
            Headers: netMail.Header{
                "On-Behalf-Of": []string{email},
            },
    }
    if err := mail.Send(c, msg); err != nil {
        c.Errorf("Couldn't send email: %v", err)
        fmt.Fprint(w, "Mail NOT send! Error")
    }else{
        fmt.Fprint(w, "Mail send.")
    }
}

NOTE:

1) ReplyTo only works in gmail if Sender and To are different.

2) Sender should have admin role in google cloud console or something@yourappid.appspotmail.com.

  • 写回答

1条回答 默认 最新

  • donglu4159 2013-12-05 10:27
    关注

    This is most likely failing because the Sender can only be

    • an email of a developer of you app, or
    • something@yourappid.appspotmail.com

    I suggest that you hard-code the sender's email, and use the On-Behalf-Of header in which you include the original sender's name/email.

    Also, WriteString accepts a single string, not a []string slice.

    The minimum modifications for your example would be:

    …
    msg := &mail.Message{
            Sender:  name + " <developer@yourapp.com>",
            To:      []string{"...@gmail.com"},
            Subject: subject,
            Body:    message,
            Headers: netMail.Header{
                "On-Behalf-Of": []string{email},
            },
    }
    …
    

    Also, you'll need to make sure the user's name doesn't actually contain an email address. That could cause you problems…

    The best would be to do as @elithrar suggested and validate your form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?