使用gomail.v2创建一个新的*Dialer。

huangapple go评论76阅读模式
英文:

Creating a new *Dialer with gomail.v2

问题

我正在使用gomail.v2来发送电子邮件,我的代码运行良好。在组合了消息msg之后,我可以直接运行以下代码:

import ("gopkg.in/gomail.v2")

  ...
  d := gomail.NewDialer("smtp.example.com", 25, "username", "password")
  return d.DialAndSend(msg)
}

当然,我想将其泛化为不特定的用户名和密码,并将其分离为自己的函数,所以我进行了桩代码:

import ("gopkg.in/gomail.v2")

  ...
  d := MyDialer()
  return d.DialAndSend(msg)
}

func MyDialer() *Dialer {
  return gomail.NewDialer("smtp.example.com", 25, "username", "password")
}

但是,Go报错说它不知道Dialer

.\email.go:42: undefined: Dialer

为什么会这样?我使用的返回类型与NewDialer相同,这不会引起任何问题。

func NewDialer(host string, port int, username, password string) *Dialer

我错过了什么?我运行了以下命令来确保我没有运行过时的软件包版本,但没有成功。

go get -u gopkg.in/gomail.v2

英文:

I'm using <a href="https://godoc.org/gopkg.in/gomail.v2">gomail.v2</a> to send emails, and my code works fine. After composing a message msg I can just run

import (&quot;gopkg.in/gomail.v2&quot;)

  ...
  d := gomail.NewDialer(&quot;smtp.example.com&quot;, 25, &quot;username&quot;, &quot;password&quot;)
  return d.DialAndSend(msg)
}

Of course I'd like to generalize this past a particular username and password and separate it into its own function, so I stubbed it out:

import (&quot;gopkg.in/gomail.v2&quot;)

  ...
  d := MyDialer()
  return d.DialAndSend(msg)
}

func MyDialer() *Dialer {
  return gomail.NewDialer(&quot;smtp.example.com&quot;, 25, &quot;username&quot;, &quot;password&quot;)
}

But go croaks, complaining that it doesn't know about Dialer.

> .\email.go:42: undefined: Dialer

Why is this? I'm using the same return type as NewDialer, which doesn't cause any problems.

func NewDialer(host string, port int, username, password string) *Dialer

What am I missing? I ran

> go get -u gopkg.in/gomail.v2

to make sure I wasn't somehow running an out of date version of the package, but no luck there.

答案1

得分: 2

*Dialer*gomail.Dialer是两种不同的类型。具体的错误是因为您的包中没有定义Dialer类型,但您需要匹配签名中的类型,而不仅仅是名称。由于gomail.NewDialer返回的是*gomail.Dialer,所以可以使用以下方式:

func MyDialer() *gomail.Dialer {
英文:

*Dialer and *gomail.Dialer are 2 different types. The specific error is because you don't have a Dialer type defined in your package, but you need to match the types in the signature, not just the name. Since gomail.NewDialer returns a *gomail.Dialer, use:

func MyDialer() *gomail.Dialer {

huangapple
  • 本文由 发表于 2017年6月7日 05:52:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/44400384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定