duandong7980 2014-11-10 08:38
浏览 74

在goroutine中发送电子邮件

I am trying to programming an authentication system with golang.

After user successfully sign up, it will send an email confirmation to the user.

I am thinking to execute the send mail function in a goroutine. The code of send mail function looks like

func Send(email, link string) error {

    // Connect to the remote SMTP server.
    c, err := smtp.Dial("127.0.0.1:2525")
    if err != nil {
        return err
    }
    // Set the sender and recipient.
    c.Mail("sender@example.org")
    c.Rcpt(email)
    // Send the email body.
    wc, err := c.Data()
    if err != nil {
        return err
    }
    defer wc.Close()
    buf := bytes.NewBufferString("Please confirm this email " + link)
    if _, err = buf.WriteTo(wc); err != nil {
        return err
    }
    return nil
}

If here an error is going to occur in the goroutine and response is already done(the user receive the response), how can I then handle the error?

  • 写回答

1条回答 默认 最新

  • donglang6656 2014-11-10 17:14
    关注

    I'm assuming:

    1. A person signs up for an account
    2. You send them a confirmation e-mail with an activation link
    3. Once they click the link their account can now "do stuff"

    If this is the case:

    You should probably record the failure or success of this send mail operation to some kind of stateful store (SQL DB, mongo, leveldb, etc), then when a user logs in (or navigates to a page) you can notify them their account still needs to be confirmed (assuming either the send operation OR the URL clicking the confirmation link never happened) and offer to resend the e-mail.

    Another option would be to make response to submitting the e-mail address wait for the e-mail to be sent (don't start a goroutine), but that might not scale well if you have many signups.. AND you would still need to maintain the state of who as clicked the activation link anyway. So the first option is better.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c