zdpgo_email

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2022 License: MIT Imports: 37 Imported by: 2

README

zdpgo_email

使用Golang操作Email

项目地址:https://github.com/zhangdapeng520/zdpgo_email

版本历史

  • v0.1.0 2022年4月8日 常用功能
  • v1.0.1 2022/5/3 新增:基于key的发送和校验
  • v1.0.2 2022/5/10 优化:新增邮箱如果失败,则返回错误而非抛出错误
  • v1.0.3 2022/5/10 新增:支持使用嵌入文件系统发送邮件附件

使用示例

发送普通邮件
package main

import (
	"github.com/zhangdapeng520/zdpgo_email"
	"github.com/zhangdapeng520/zdpgo_yaml"
)

func main() {
	// 读取配置
	y := zdpgo_yaml.New()
	var config zdpgo_email.Config
	err := y.ReadDefaultConfig(&config)
	if err != nil {
		panic(err)
	}

	// 创建邮件对象
	email := zdpgo_email.New(config)

	// 简单设置 log 参数
	email.SendText("这是一封测试邮件", "我在用Golang发邮件。。。", "lxgzhw@163.com")
}
发送HTML邮件
package main

import (
	"github.com/zhangdapeng520/zdpgo_email"
	"github.com/zhangdapeng520/zdpgo_yaml"
)

func main() {
	// 读取配置
	y := zdpgo_yaml.New()
	var config zdpgo_email.Config
	err := y.ReadDefaultConfig(&config)
	if err != nil {
		panic(err)
	}

	// 创建邮件对象
	email := zdpgo_email.New(config)

	//设置文件发送的内容
	content := `
   <h3><a href="https://www.baidu.com">欢迎来到张大鹏的主页</a></h3>
<br/>
<table border="0" style="font-family: '微软雅黑 Light';" cellpadding="3px">
    <tr>
        <td> 1 </td>
        <td><a href="https://www.baidu.com">GO 中 defer的实现原理</a></td>
    </tr>
    <tr>
        <td> 2 </td>
        <td><a href="https://www.baidu.com">GO 中 Chan 实现原理分享</a></td>
    </tr>
    <tr>
        <td> 3 </td>
        <td><a href="https://www.baidu.com">GO 中 map 的实现原理</a></td>
    </tr>
    <tr>
        <td> 4 </td>
        <td><a href="https://www.baidu.com">GO 中 slice 的实现原理</a></td>
    </tr>
</table>
`

	// 发送HTML邮件
	email.SendHtml("这是一封测试邮件", content, "lxgzhw@163.com")
}

Documentation

Index

Constants

View Source
const (
	MaxLineLength = 76 // MaxLineLength RFC 2045的最大线长是多少

)

Variables

View Source
var (
	// ErrAlreadyLoggedIn is returned if Login or Authenticate is called when the
	// client is already logged in.
	ErrAlreadyLoggedIn = errors.New("Already logged in")
	// ErrTLSAlreadyEnabled is returned if StartTLS is called when TLS is already
	// enabled.
	ErrTLSAlreadyEnabled = errors.New("TLS is already enabled")
	// ErrLoginDisabled is returned if Login or Authenticate is called when the
	// server has disabled authentication. Most of the time, calling enabling TLS
	// solves the problem.
	ErrLoginDisabled = errors.New("Login is disabled in current state")
)
View Source
var (
	// ErrNoMailboxSelected is returned if a command that requires a mailbox to be
	// selected is called when there isn't.
	ErrNoMailboxSelected = errors.New("No mailbox selected")

	// ErrExtensionUnsupported is returned if a command uses a extension that
	// is not supported by the server.
	ErrExtensionUnsupported = errors.New("The required extension is not supported by the server")
)
View Source
var ErrAlreadyLoggedOut = errors.New("Already logged out")

ErrAlreadyLoggedOut is returned if Logout is called when the client is already logged out.

View Source
var ErrMissingBoundary = errors.New("没有为多部分实体找到边界")

ErrMissingBoundary 当多个部分的实体没有给定边界时返回

View Source
var ErrMissingContentType = errors.New("没有找到MIME实体的内容类型")

ErrMissingContentType 是返回时,没有“内容类型”的头MIME实体

View Source
var ErrNotLoggedIn = errors.New("Not logged in")

ErrNotLoggedIn is returned if a function that requires the client to be logged in is called then the client isn't.

Functions

func ConvertToUTF8 added in v1.0.0

func ConvertToUTF8(b []byte, charset string) ([]byte, error)

Convert gbk等转为utf-8 bytes

func Decode added in v1.0.0

func Decode(encoding byte, text string) ([]byte, error)

func IsGBK added in v1.0.0

func IsGBK(data []byte) bool

func IsUTF8 added in v1.0.0

func IsUTF8(data []byte) bool

func IsUTF8String added in v1.0.0

func IsUTF8String(s string) bool

func MailDecodeHeader added in v1.0.0

func MailDecodeHeader(s string) (string, error)

MailDecodeHeader 自行处理strHeader,类似=?GB2312?B?1tDOxLi9vP6y4srU?=

func QDecode added in v1.0.0

func QDecode(s string) ([]byte, error)

QDecode decodes a Q encoded string.

Types

type Attachment

type Attachment struct {
	Filename    string
	ContentType string
	Header      textproto.MIMEHeader
	Content     []byte
	HTMLRelated bool
}

Attachment 是表示电子邮件附件的结构体。

type CommonError added in v1.0.0

type CommonError struct {
	Cause string
}

func (CommonError) Error added in v1.0.0

func (e CommonError) Error() string

type Config added in v0.1.1

type Config struct {
	SmtpConfigs []string `yaml:"smtp_configs" json:"smtp_configs"` // 发送者的名字
	ImapConfigs []string `yaml:"imap_configs" json:"imap_configs"` // 发送者的名字
	Fs          embed.FS // 嵌入文件系统
	IsUseFs     bool     `yaml:"is_use_fs" json:"is_use_fs" env:"is_use_fs"` // 是否使用fs嵌入文件系统
}

Config 配置类

type ConfigImap added in v1.0.0

type ConfigImap struct {
	Server         string `yaml:"server" json:"server" env:"server"`        // 服务器地址
	Timeout        int    `yaml:"timeout" json:"timeout" env:"timeout"`     // 连接超时时间,默认30秒
	Username       string `yaml:"username" json:"username" env:"username"`  // 用户名
	Email          string `yaml:"email" json:"email" env:"email"`           // 邮箱
	Password       string `yaml:"password" json:"password" env:"password"`  // 密码
	HeaderTagName  string `yaml:"header_tag_name" json:"header_tag_name"`   // 请求头标记名
	HeaderTagValue string `yaml:"header_tag_value" json:"header_tag_value"` // 请求头标记默认值
}

ConfigImap EmailImap的相关配置

type ConfigSmtp added in v1.0.1

type ConfigSmtp struct {
	Username       string `yaml:"username" json:"username"`                 // 发送者的名字
	Email          string `yaml:"email" json:"email"`                       // 发送者的邮箱
	Password       string `yaml:"password" json:"password"`                 // 发送者的邮箱的校验密码(不一定是登陆密码)
	SmtpHost       string `yaml:"smtp_host" json:"smtp_host"`               // 邮箱服务器的主机地址(域名)
	SmtpPort       int    `yaml:"smtp_port" json:"smtp_port"`               // 端口
	Id             string `yaml:"id" json:"id"`                             // 权限ID,可以不填
	IsSSL          bool   `yaml:"is_ssl" json:"is_ssl"`                     // 是否为SSL模式
	HeaderTagName  string `yaml:"header_tag_name" json:"header_tag_name"`   // 请求头标记名
	HeaderTagValue string `yaml:"header_tag_value" json:"header_tag_value"` // 请求头标记值
}

type Dialer added in v1.0.0

type Dialer interface {
	// Dial connects to the given address.
	Dial(network, addr string) (net.Conn, error)
}

type Email

type Email struct {
	Send    *EmailSmtp
	Receive *EmailImap
	Fs      embed.FS // 嵌入的文件系统
	Random  *zdpgo_random.Random
	Yaml    *zdpgo_yaml.Yaml
}

func New

func New() (email *Email, err error)

New 新建邮件对象,支持发送邮件和接收邮件

func NewWithConfig added in v1.0.1

func NewWithConfig(config Config) (email *Email, err error)

NewWithConfig 根据配置文件,创建邮件对象

type EmailImap added in v1.0.0

type EmailImap struct {

	// A channel to which unilateral updates from the server will be sent. An
	// update can be one of: *StatusUpdate, *MailboxUpdate, *MessageUpdate,
	// *ExpungeUpdate. Note that blocking this channel blocks the whole client,
	// so it's recommended to use a separate goroutine and a buffered channel to
	// prevent deadlocks.
	Updates chan<- Update

	// ErrorLog specifies an optional logger for errors accepting connections and
	// unexpected behavior from handlers. By default, logging goes to os.Stderr
	// via the log package's standard logger. The logger must be safe to use
	// simultaneously from multiple goroutines.
	ErrorLog imap.Logger

	// Timeout specifies a maximum amount of time to wait on a command.
	//
	// A Timeout of zero means no timeout. This is the default.
	Timeout time.Duration
	Config  *ConfigImap // 配置对象
	// contains filtered or unexported fields
}

EmailImap IMAP客户端

func Dial added in v1.0.0

func Dial(addr string) (*EmailImap, error)

Dial connects to an IMAP server using an unencrypted connection.

func DialTLS added in v1.0.0

func DialTLS(addr string, tlsConfig *tls.Config) (*EmailImap, error)

DialTLS 使用加密连接连接IMAP服务器。

func DialWithDialer added in v1.0.0

func DialWithDialer(dialer Dialer, addr string) (*EmailImap, error)

DialWithDialer connects to an IMAP server using an unencrypted connection using dialer.Dial.

Among other uses, this allows to apply a dial timeout.

func DialWithDialerTLS added in v1.0.0

func DialWithDialerTLS(dialer Dialer, addr string, tlsConfig *tls.Config) (*EmailImap, error)

DialWithDialerTLS 使用dialer.Dial使用加密连接连接IMAP服务器。在其他用途中,这允许应用拨号超时。

func NewEmailImap added in v1.0.0

func NewEmailImap(conn net.Conn) (*EmailImap, error)

NewEmailImap creates a new client from an existing connection.

func NewEmailImapWithConfig added in v1.0.0

func NewEmailImapWithConfig(config ConfigImap) (e *EmailImap, err error)

NewEmailImapWithConfig 根据配置信息,创建EmailImap实例

func NewEmailImapWithServer added in v1.0.0

func NewEmailImapWithServer(addr string, tlsConfig *tls.Config) (e *EmailImap, err error)

NewEmailImapWithServer 根据邮件服务器地址,创建邮件Imap对象

func (*EmailImap) Append added in v1.0.0

func (c *EmailImap) Append(mbox string, flags []string, date time.Time, msg imap.Literal) error

Append appends the literal argument as a new message to the end of the specified destination mailbox. This argument SHOULD be in the format of an RFC 2822 message. flags and date are optional arguments and can be set to nil and the empty struct.

func (*EmailImap) Authenticate added in v1.0.0

func (c *EmailImap) Authenticate(auth sasl.Client) error

Authenticate indicates a SASL authentication mechanism to the server. If the server supports the requested authentication mechanism, it performs an authentication protocol exchange to authenticate and identify the client.

func (*EmailImap) Capability added in v1.0.0

func (c *EmailImap) Capability() (map[string]bool, error)

Capability requests a listing of capabilities that the server supports. Capabilities are often returned by the server with the greeting or with the STARTTLS and LOGIN responses, so usually explicitly requesting capabilities isn't needed.

Most of the time, Support should be used instead.

func (*EmailImap) Check added in v1.0.0

func (c *EmailImap) Check() error

Check requests a checkpoint of the currently selected mailbox. A checkpoint refers to any implementation-dependent housekeeping associated with the mailbox that is not normally executed as part of each command.

func (*EmailImap) Close added in v1.0.0

func (c *EmailImap) Close() error

Close permanently removes all messages that have the \Deleted flag set from the currently selected mailbox, and returns to the authenticated state from the selected state.

func (*EmailImap) Copy added in v1.0.0

func (c *EmailImap) Copy(seqset *imap.SeqSet, dest string) error

Copy copies the specified message(s) to the end of the specified destination mailbox.

func (*EmailImap) Create added in v1.0.0

func (c *EmailImap) Create(name string) error

Create 创建具有给定名称的邮箱。

func (*EmailImap) Delete added in v1.0.0

func (c *EmailImap) Delete(name string) error

Delete 永久删除具有给定名称的邮箱。

func (*EmailImap) Enable added in v1.0.0

func (c *EmailImap) Enable(caps []string) ([]string, error)

Enable requests the server to enable the named extensions. The extensions which were successfully enabled are returned.

See RFC 5161 section 3.1.

func (*EmailImap) Execute added in v1.0.0

func (c *EmailImap) Execute(cmdr imap.Commander, h responses.Handler) (*imap.StatusResp, error)

Execute executes a generic command. cmdr is a value that can be converted to a raw command and h is a response handler. The function returns when the command has completed or failed, in this case err is nil. A non-nil err value indicates a network error.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*EmailImap) Expunge added in v1.0.0

func (c *EmailImap) Expunge(ch chan uint32) error

Expunge permanently removes all messages that have the \Deleted flag set from the currently selected mailbox. If ch is not nil, sends sequence IDs of each deleted message to this channel.

func (*EmailImap) Fetch added in v1.0.0

func (c *EmailImap) Fetch(seqset *imap.SeqSet, items []imap.FetchItem, ch chan *imap.Message) error

Fetch retrieves data associated with a message in the mailbox. See RFC 3501 section 6.4.5 for a list of items that can be requested.

func (*EmailImap) Idle added in v1.0.0

func (c *EmailImap) Idle(stop <-chan struct{}, opts *IdleOptions) error

Idle indicates to the server that the client is ready to receive unsolicited mailbox update messages. When the client wants to send commands again, it must first close stop.

If the server doesn't support IDLE, go-imap falls back to polling.

func (*EmailImap) IsSendSuccessByKey added in v1.0.1

func (e *EmailImap) IsSendSuccessByKey(from string, key string) bool

IsSendSuccessByKey 根据key判断邮件是否发送成功

func (*EmailImap) IsTLS added in v1.0.0

func (c *EmailImap) IsTLS() bool

IsTLS checks if this client's connection has TLS enabled.

func (*EmailImap) List added in v1.0.0

func (c *EmailImap) List(ref, name string, ch chan *imap.MailboxInfo) error

List 从客户端可用的所有名称的完整集合中返回名称的子集。 空的name参数是一个特殊的请求,要求返回层次结构分隔符和引用中给出的名称的根名称。 字符“*”是一个通配符,在这个位置匹配零个或多个字符。字符“%”类似于“*”,但它不匹配层次分隔符。

func (*EmailImap) LoggedOut added in v1.0.0

func (c *EmailImap) LoggedOut() <-chan struct{}

LoggedOut returns a channel which is closed when the connection to the server is closed.

func (*EmailImap) Login added in v1.0.0

func (c *EmailImap) Login(username, password string) error

Login identifies the client to the server and carries the plaintext password authenticating this user.

func (*EmailImap) Logout added in v1.0.0

func (c *EmailImap) Logout() error

Logout gracefully closes the connection.

func (*EmailImap) Lsub added in v1.0.0

func (c *EmailImap) Lsub(ref, name string, ch chan *imap.MailboxInfo) error

Lsub 从用户声明为“活动”或“订阅”的名称集中返回名称的子集。

func (*EmailImap) Mailbox added in v1.0.0

func (c *EmailImap) Mailbox() *imap.MailboxStatus

Mailbox returns the selected mailbox. It returns nil if there isn't one.

func (*EmailImap) Move added in v1.0.0

func (c *EmailImap) Move(seqset *imap.SeqSet, dest string) error

Move moves the specified message(s) to the end of the specified destination mailbox.

If the server doesn't support the MOVE extension defined in RFC 6851, go-imap will fallback to copy, store and expunge.

func (*EmailImap) Noop added in v1.0.0

func (c *EmailImap) Noop() error

Noop always succeeds and does nothing.

It can be used as a periodic poll for new messages or message status updates during a period of inactivity. It can also be used to reset any inactivity autologout timer on the server.

func (*EmailImap) Rename added in v1.0.0

func (c *EmailImap) Rename(existingName, newName string) error

Rename 更改邮箱的名称。

func (*EmailImap) Search added in v1.0.0

func (c *EmailImap) Search(criteria *imap.SearchCriteria) (seqNums []uint32, err error)

Search searches the mailbox for messages that match the given searching criteria. Searching criteria consist of one or more test keys. The response contains a list of message sequence IDs corresponding to those messages that match the searching criteria. When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys. Criteria must be UTF-8 encoded. See RFC 3501 section 6.4.4 for a list of searching criteria. When no criteria has been set, all messages in the mailbox will be searched using ALL criteria.

func (*EmailImap) SearchBF added in v1.0.0

func (e *EmailImap) SearchBF(bf *PreFilter, af *PostFilter) ([]MailMessage, error)

func (*EmailImap) SearchByDefaultTag added in v1.0.0

func (e *EmailImap) SearchByDefaultTag(from string, startTime string) ([]MailMessage, error)

SearchByDefaultTag 根据默认的tag进行搜索

func (*EmailImap) SearchByKey added in v1.0.1

func (e *EmailImap) SearchByKey(from string, startTime string, key string) ([]MailMessage, error)

SearchByKey 根据时间和key搜索邮件

func (*EmailImap) SearchByKeyToday added in v1.0.1

func (e *EmailImap) SearchByKeyToday(from string, key string) ([]MailMessage, error)

SearchByKeyToday 根据key搜索今天的邮件

func (*EmailImap) SearchByTag added in v1.0.0

func (e *EmailImap) SearchByTag(from string, startTime string, tagKey, tagValue string) ([]MailMessage, error)

SearchByTag 根据标签进行搜索

func (*EmailImap) Select added in v1.0.0

func (c *EmailImap) Select(name string, readOnly bool) (*imap.MailboxStatus, error)

Select 选择一个邮箱,以便可以访问该邮箱中的消息。 在尝试新的选择之前,将取消当前选中的任何邮箱。 即使readOnly参数设置为false,服务器也可以决定以只读模式打开邮箱。

func (*EmailImap) SetDebug added in v1.0.0

func (c *EmailImap) SetDebug(w io.Writer)

SetDebug defines an io.Writer to which all network activity will be logged. If nil is provided, network activity will not be logged.

func (*EmailImap) SetState added in v1.0.0

func (c *EmailImap) SetState(state imap.ConnState, mailbox *imap.MailboxStatus)

SetState sets this connection's internal state.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*EmailImap) StartTLS added in v1.0.0

func (c *EmailImap) StartTLS(tlsConfig *tls.Config) error

StartTLS starts TLS negotiation.

func (*EmailImap) State added in v1.0.0

func (c *EmailImap) State() imap.ConnState

State returns the current connection state.

func (*EmailImap) Status added in v1.0.0

func (c *EmailImap) Status(name string, items []imap.StatusItem) (*imap.MailboxStatus, error)

Status requests the status of the indicated mailbox. It does not change the currently selected mailbox, nor does it affect the state of any messages in the queried mailbox.

See RFC 3501 section 6.3.10 for a list of items that can be requested.

func (*EmailImap) Store added in v1.0.0

func (c *EmailImap) Store(seqset *imap.SeqSet, item imap.StoreItem, value interface{}, ch chan *imap.Message) error

Store alters data associated with a message in the mailbox. If ch is not nil, the updated value of the data will be sent to this channel. See RFC 3501 section 6.4.6 for a list of items that can be updated.

func (*EmailImap) Subscribe added in v1.0.0

func (c *EmailImap) Subscribe(name string) error

Subscribe 将指定的邮箱名称添加到服务器的“活动”或“订阅”邮箱集。

func (*EmailImap) Support added in v1.0.0

func (c *EmailImap) Support(cap string) (bool, error)

Support checks if cap is a capability supported by the server. If the server hasn't sent its capabilities yet, Support requests them.

func (*EmailImap) SupportAuth added in v1.0.0

func (c *EmailImap) SupportAuth(mech string) (bool, error)

SupportAuth checks if the server supports a given authentication mechanism.

func (*EmailImap) SupportStartTLS added in v1.0.0

func (c *EmailImap) SupportStartTLS() (bool, error)

SupportStartTLS checks if the server supports STARTTLS.

func (*EmailImap) Terminate added in v1.0.0

func (c *EmailImap) Terminate() error

Terminate closes the tcp connection

func (*EmailImap) UidCopy added in v1.0.0

func (c *EmailImap) UidCopy(seqset *imap.SeqSet, dest string) error

UidCopy is identical to Copy, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*EmailImap) UidFetch added in v1.0.0

func (c *EmailImap) UidFetch(seqset *imap.SeqSet, items []imap.FetchItem, ch chan *imap.Message) error

UidFetch is identical to Fetch, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*EmailImap) UidMove added in v1.0.0

func (c *EmailImap) UidMove(seqset *imap.SeqSet, dest string) error

UidMove is identical to Move, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*EmailImap) UidSearch added in v1.0.0

func (c *EmailImap) UidSearch(criteria *imap.SearchCriteria) (uids []uint32, err error)

UidSearch is identical to Search, but UIDs are returned instead of message sequence numbers.

func (*EmailImap) UidStore added in v1.0.0

func (c *EmailImap) UidStore(seqset *imap.SeqSet, item imap.StoreItem, value interface{}, ch chan *imap.Message) error

UidStore is identical to Store, but seqset is interpreted as containing unique identifiers instead of message sequence numbers.

func (*EmailImap) Unselect added in v1.0.0

func (c *EmailImap) Unselect() error

Unselect frees server's resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as Close, except that no messages are permanently removed from the currently selected mailbox.

If client does not support the UNSELECT extension, ErrExtensionUnsupported is returned.

func (*EmailImap) Unsubscribe added in v1.0.0

func (c *EmailImap) Unsubscribe(name string) error

Unsubscribe 从服务器的“活动”或“订阅”邮箱集中删除指定的邮箱名称。

func (*EmailImap) Upgrade added in v1.0.0

func (c *EmailImap) Upgrade(upgrader imap.ConnUpgrader) error

Upgrade a connection, e.g. wrap an unencrypted connection with an encrypted tunnel.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

func (*EmailImap) Writer added in v1.0.0

func (c *EmailImap) Writer() *imap.Writer

Writer returns the imap.Writer for this EmailImap's connection.

This function should not be called directly, it must only be used by libraries implementing extensions of the IMAP protocol.

type EmailSmtp added in v1.0.0

type EmailSmtp struct {
	ReplyTo     []string             `json:"reply_to" yaml:"reply_to" env:"reply_to"`
	From        string               `json:"from" yaml:"from" env:"from"`          // 发送者
	To          []string             `json:"to" yaml:"to" env:"to"`                // 接收者
	Bcc         []string             `json:"bcc" yaml:"bcc" env:"bcc"`             // 密送
	Cc          []string             `json:"cc" yaml:"cc" env:"cc"`                // 抄送
	Subject     string               `json:"subject" yaml:"subject" env:"subject"` // 主题,邮件标题
	Text        []byte               `json:"text" yaml:"text" env:"text"`
	HTML        []byte               `json:"html" yaml:"html" env:"html"`
	Sender      string               `json:"sender" yaml:"sender" env:"sender"`
	Headers     textproto.MIMEHeader `json:"headers" yaml:"headers" env:"headers"`             // 协议头
	Attachments []*Attachment        `json:"attachments" yaml:"attachments" env:"attachments"` // 附件
	ReadReceipt []string             `json:"read_receipt" yaml:"read_receipt" env:"read_receipt"`
	Config      *ConfigSmtp          `json:"config" yaml:"config" env:"config"` // 配置对象

	Fs embed.FS // 嵌入文件系统
	// contains filtered or unexported fields
}

EmailSmtp 是用于电子邮件消息的类型吗

func NewEmailFromReader

func NewEmailFromReader(r io.Reader) (email *EmailSmtp, err error)

NewEmailFromReader 从一个io.Reade读取字节流, 并返回包含已解析数据的电子邮件结构体。 该函数需要RFC 5322格式的数据。

func NewEmailSmtp added in v1.0.0

func NewEmailSmtp() (email *EmailSmtp, err error)

NewEmailSmtp 创建邮件对象

func NewEmailSmtpWithConfig added in v1.0.0

func NewEmailSmtpWithConfig(config ConfigSmtp) (email *EmailSmtp, err error)

func (*EmailSmtp) Attach added in v1.0.0

func (e *EmailSmtp) Attach(r io.Reader, filename string, c string) (a *Attachment, err error)

Attach 从io.Reader读取内容作为邮件的附件 要求参数包含一个io.Reader输入流, 文件名, Content-Type @param r:输入流 @param filename:文件名,不包含后缀 @param c:Content-Type

func (*EmailSmtp) AttachFile added in v1.0.0

func (e *EmailSmtp) AttachFile(filename string) (a *Attachment, err error)

AttachFile 用来给邮件内容添加附件 @param filename 文件名,一般是相对路径 如果文件能够引用成功,就创建一个Attachment附件对象 This Attachment is then appended to the slice of Email.Attachments. The function will then return the Attachment for reference, as well as nil for the error, if successful.

func (*EmailSmtp) Bytes added in v1.0.0

func (e *EmailSmtp) Bytes() ([]byte, error)

Bytes 将Email对象转换为[]字节表示,包括所有需要的MIMEHeaders、边界等。

func (*EmailSmtp) GetGoMailSendCloser added in v1.0.0

func (e *EmailSmtp) GetGoMailSendCloser() (gomail.SendCloser, error)

GetGoMailSendCloser 获取gomail对象 @param host 服务器地址 @param port 服务器端口 @param username 用户名 @param password 密码

func (*EmailSmtp) Send added in v1.0.0

func (e *EmailSmtp) Send(addr string, a smtp.Auth) error

Send 使用给定主机和SMTP身份验证(可选)的电子邮件,返回SMTP抛出的任何错误 这个函数合并 To, Cc, and Bcc 字段并调用 smtp.SendMail 方法,使用 Email.Bytes() 输出消息

func (*EmailSmtp) SendEmail added in v1.0.0

func (e *EmailSmtp) SendEmail(title, content, attach string, isHtml bool, emails []string, ccEmails []string,
	bccEmails []string) error

SendEmail 封装发送文本邮件的方法 @param title 邮件标题 @param content 邮件内容 @param attach 附件 @param isHtml 是否为HTML内容 @param emails 普通收件人地址列表 @param ccEmails 抄送人邮箱地址列表 @param bccEmails 密送人邮箱地址列表

func (*EmailSmtp) SendGoMail added in v1.0.0

func (e *EmailSmtp) SendGoMail(emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) (err error)

SendGoMail 使用gomail发送邮件 @param emailTitle 邮件标题 @param emailBody 邮件内容 @param emailAttachments 邮件附件 @param toEmails 收件人邮箱 @return err 异常信息

func (*EmailSmtp) SendGoMailWithFs added in v1.0.3

func (e *EmailSmtp) SendGoMailWithFs(emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) (err error)

SendGoMailWithFs 使用嵌入文件系统发送邮件

func (*EmailSmtp) SendHtml added in v1.0.0

func (e *EmailSmtp) SendHtml(title, content string, emails ...string)

SendHtml 发送HTML邮件 @param toEmail 发送给哪个邮箱,也就是收件人 @param title 邮件标题 @param content 邮件内容

func (*EmailSmtp) SendHtmlAndAttach added in v1.0.0

func (e *EmailSmtp) SendHtmlAndAttach(title, content, attach string, emails ...string)

SendHtmlAndAttach 发送HTML邮件且能够携带附件 @param toEmail 发送给哪个邮箱,也就是收件人 @param title 邮件标题 @param content 邮件内容 @param attach 附件

func (*EmailSmtp) SendText added in v1.0.0

func (e *EmailSmtp) SendText(title, content string, emails ...string)

SendText 发送文本邮件 @param toEmail 发送给哪个邮箱,也就是收件人 @param title 邮件标题 @param content 邮件内容

func (*EmailSmtp) SendTextAndAttach added in v1.0.0

func (e *EmailSmtp) SendTextAndAttach(title, content, attach string, emails ...string)

SendTextAndAttach 发送文本文件,且能够携带附件 @param toEmail 发送给哪个邮箱,也就是收件人 @param title 邮件标题 @param content 邮件内容 @param attach 附件

func (*EmailSmtp) SendWithDefaultTag added in v1.0.0

func (e *EmailSmtp) SendWithDefaultTag(emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) error

SendWithDefaultTag 使用默认的tag和value发送邮件

func (*EmailSmtp) SendWithDefaultTagWithFs added in v1.0.3

func (e *EmailSmtp) SendWithDefaultTagWithFs(emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) error

SendWithDefaultTagWithFs 使用默认标签和嵌入文件系统发送邮件

func (*EmailSmtp) SendWithKey added in v1.0.1

func (e *EmailSmtp) SendWithKey(emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) (string, error)

SendWithKey 生成一个随机的key作为邮件的标识进行发送

func (*EmailSmtp) SendWithStartTLS added in v1.0.0

func (e *EmailSmtp) SendWithStartTLS(addr string, a smtp.Auth, t *tls.Config) error

SendWithStartTLS 使用带有可选TLS秘密的STARTTLS通过TLS发送电子邮件。 如果您需要连接到使用不受信任证书的主机,TLS配置将非常有用。

func (*EmailSmtp) SendWithTLS added in v1.0.0

func (e *EmailSmtp) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error

SendWithTLS 通过可选的tls密钥发送电子邮件。 如果您需要连接到使用不受信任证书的主机,TLS配置将非常有用。

func (*EmailSmtp) SendWithTag added in v1.0.0

func (e *EmailSmtp) SendWithTag(tagKey, tagValue, emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) error

SendWithTag 通过标签发送邮件

func (*EmailSmtp) SendWithTagAndFs added in v1.0.3

func (e *EmailSmtp) SendWithTagAndFs(tagKey, tagValue, emailTitle string, emailBody string, emailAttachments []string,
	toEmails ...string) error

SendWithTagAndFs 使用标签和嵌入文件系统发送邮件

type ExpungeUpdate added in v1.0.0

type ExpungeUpdate struct {
	SeqNum uint32
}

ExpungeUpdate 更新垃圾箱

type IdleOptions added in v1.0.0

type IdleOptions struct {
	// LogoutTimeout is used to avoid being logged out by the server when
	// idling. Each LogoutTimeout, the IDLE command is restarted. If set to
	// zero, a default is used. If negative, this behavior is disabled.
	LogoutTimeout time.Duration
	// Poll interval when the server doesn't support IDLE. If zero, a default
	// is used. If negative, polling is always disabled.
	PollInterval time.Duration
}

IdleOptions holds options for Client.Idle.

type MailMessage added in v1.0.0

type MailMessage struct {
	Subject        string   // 邮件标题
	From           string   // 发件人
	To             string   // 收件人
	HeaderTagName  string   // 请求头中的标识
	HeaderTagValue string   // 请求头中的标识
	Body           string   // 内容
	Attachments    []string // 附件
}

MailMessage 邮件消息

type MailboxUpdate added in v1.0.0

type MailboxUpdate struct {
	Mailbox *imap.MailboxStatus
}

MailboxUpdate 更新邮箱

type MessageUpdate added in v1.0.0

type MessageUpdate struct {
	Message *imap.Message
}

MessageUpdate 更新发件箱

type PostFilter added in v1.0.0

type PostFilter struct {
	Subject        string
	From           string
	To             string
	HeaderTagName  string
	HeaderTagValue string
	SentSince      string //日期格式字符串 "2006-01-02"
	Body           []string
	Attachments    []string //filenames
}

PostFilter qq等邮箱使用中文过滤时会报错:imap: cannot send literal: no continuation request received 先用临时解决办法吧,PreFilter过滤条件不要输入中文,获取结果后再次过滤

type PreFilter added in v1.0.0

type PreFilter struct {
	Seen           interface{} //true,false,nil
	Subject        string
	From           string
	To             string
	HeaderTagName  string
	HeaderTagValue string
	SentSince      string //日期格式字符串 "2006-01-02"
	Body           []string
}

type SendConfig added in v1.0.0

type SendConfig struct {
	Uid         string   //自定义的邮件头
	From        string   //发件人邮箱
	To          []string //收件人邮箱,可发给多人
	Subject     string   //邮件主题
	Body        string   //邮件内容
	Attachments []string //file path
}

type StatusUpdate added in v1.0.0

type StatusUpdate struct {
	Status *imap.StatusResp
}

StatusUpdate 更新状态

type Update added in v1.0.0

type Update interface {
	// contains filtered or unexported methods
}

Update 更新接口

type WordDecoder added in v1.0.0

type WordDecoder struct {
	// CharsetReader, if non-nil, defines a function to generate
	// charset-conversion readers, converting from the provided
	// charset into UTF-8.
	// Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets
	// are handled by default.
	// One of the CharsetReader's result values must be non-nil.
	CharsetReader func(charset string, input io.Reader) (io.Reader, error)
}

A WordDecoder decodes MIME headers containing RFC 2047 encoded-words.

func (*WordDecoder) Convert added in v1.0.0

func (d *WordDecoder) Convert(buf *strings.Builder, charset string, content []byte) error

func (*WordDecoder) DecodeHeader added in v1.0.0

func (d *WordDecoder) DecodeHeader(header string) (string, error)

DecodeHeader decodes all encoded-words of the given string. It returns an error if and only if CharsetReader of d returns an error.

Directories

Path Synopsis
examples
Package gomail provides a simple interface to compose emails and to mail them efficiently.
Package gomail provides a simple interface to compose emails and to mail them efficiently.
Implements the IMAP ID Extension, defined in RFC 2971.
Implements the IMAP ID Extension, defined in RFC 2971.
Package imap implements IMAP4rev1 (RFC 3501).
Package imap implements IMAP4rev1 (RFC 3501).
backend
Package backend defines an IMAP server backend interface.
Package backend defines an IMAP server backend interface.
backend/backendutil
Package backendutil provides utility functions to implement IMAP backends.
Package backendutil provides utility functions to implement IMAP backends.
backend/memory
A memory backend.
A memory backend.
client
Package client provides an IMAP client.
Package client provides an IMAP client.
commands
Package commands implements IMAP commands defined in RFC 3501.
Package commands implements IMAP commands defined in RFC 3501.
responses
IMAP responses defined in RFC 3501.
IMAP responses defined in RFC 3501.
server
Package server provides an IMAP server.
Package server provides an IMAP server.
utf7
Package utf7 implements modified UTF-7 encoding defined in RFC 3501 section 5.1.3
Package utf7 implements modified UTF-7 encoding defined in RFC 3501 section 5.1.3
Package message implements reading and writing multipurpose messages.
Package message implements reading and writing multipurpose messages.
charset
Package charset provides functions to decode and encode charsets.
Package charset provides functions to decode and encode charsets.
mail
Package mail1 implements reading and writing mail1 messages.
Package mail1 implements reading and writing mail1 messages.
textproto
Package textproto implements low-level manipulation of MIME messages.
Package textproto implements low-level manipulation of MIME messages.
Library for Simple Authentication and Security Layer (SASL) defined in RFC 4422.
Library for Simple Authentication and Security Layer (SASL) defined in RFC 4422.
A writer that wraps long text lines to a specified length.
A writer that wraps long text lines to a specified length.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL