• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package utils
17
18import (
19	"crypto/tls"
20	"fmt"
21	"github.com/sirupsen/logrus"
22	"gopkg.in/gomail.v2"
23	"strconv"
24	"strings"
25)
26
27type MailConfig struct {
28	Host     string `key:"host" default:""`
29	Port     string `key:"port" default:""`
30	port     int
31	User     string `key:"user" default:""`
32	Password string `key:"password" default:""`
33	From     string `key:"from" default:""`
34	To       string `key:"to" default:""`
35	toList   []string
36}
37
38var mailConfig MailConfig
39
40func init() {
41	ParseFromConfigFile("mail", &mailConfig)
42	if mailConfig.Host != "" {
43		var err error
44		if mailConfig.port, err = strconv.Atoi(mailConfig.Port); err != nil {
45			panic(fmt.Errorf("parse mail port err: %v", err))
46		}
47		mailConfig.toList = strings.Split(mailConfig.To, ",")
48	}
49}
50
51func SendMail(subject string, body string, attachments ...string) error {
52	if mailConfig.Host == "" {
53		logrus.Info("mail not configured, do nothing")
54		return nil
55	}
56	dail := gomail.NewDialer(mailConfig.Host, mailConfig.port, mailConfig.User, mailConfig.Password)
57	dail.TLSConfig = &tls.Config{InsecureSkipVerify: true, ServerName: mailConfig.Host}
58	msg := gomail.NewMessage()
59	msg.SetBody("text/html", body)
60	msg.SetHeader("From", mailConfig.From)
61	msg.SetHeader("To", mailConfig.toList...)
62	msg.SetHeader("Subject", subject)
63	for _, a := range attachments {
64		msg.Attach(a)
65	}
66	return dail.DialAndSend(msg)
67}
68