Java mail使用freemarker作为内容模板发送邮件,支持附件

13 篇文章 0 订阅

完整项目路径 https://github.com/f529352479/mailUtil.git

标签: FreeMarker

代码片段(5)[全屏查看所有代码]

1. [代码]邮件发送配置信息加载类     

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

package com.common.util.mail;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

/**

 * 邮件发送配置信息加载类

 *

 * @date 2014年4月26日 下午2:52:06

 * @author

 * @Description:

 * @project mailUtil

 */

public class ConfigLoader {

    //日志记录对象

    private static Logger log = LoggerFactory.getLogger(ConfigLoader.class);

    // 配置文件路径

    private static String mailPath = "mail/mail.properties";

    // 邮件发送SMTP主机

    private static String server;

    // 发件人邮箱地址

    private static String sender;

    // 发件人邮箱用户名

    private static String username;

    // 发件人邮箱密码

    private static String password;

    // 发件人显示昵称

    private static String nickname;

    static {

        // 类初始化后加载配置文件

        InputStream in = ConfigLoader.class.getClassLoader()

                .getResourceAsStream(mailPath);

        Properties props = new Properties();

        try {

            props.load(in);

        } catch (IOException e) {

            log.error("load mail setting error,pleace check the file path:"

                    + mailPath);

            log.error(e.toString(), e);

        }

        server = props.getProperty("mail.server");

        sender = props.getProperty("mail.sender");

        username = props.getProperty("mail.username");

        password = props.getProperty("mail.password");

        nickname = props.getProperty("mail.nickname");

        log.debug("load mail setting success,file path:" + mailPath);

    }

 

    public static String getServer() {

        return server;

    }

 

    public static String getSender() {

        return sender;

    }

 

    public static String getUsername() {

        return username;

    }

 

    public static String getPassword() {

        return password;

    }

 

    public static String getNickname() {

        return nickname;

    }

 

    public static void setMailPath(String mailPath) {

        ConfigLoader.mailPath = mailPath;

    }

 

}

2. [代码]邮件发送实现类     

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

package com.common.util.mail;

 

import java.io.UnsupportedEncodingException;

import java.util.Properties;

 

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

/**

 * 邮件发送实现类

 *

 * @date 2014年4月26日 上午10:16:34

 * @author

 * @Description:

 * @project mailUtil

 */

public class MailSender {

    private MimeMessage mimeMsg; // MIME邮件对象

    private Session session; // 邮件会话对象

    private Properties props; // 系统属性

    private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成

    private String username;// 发件人的用户名

    private String password;// 发件人的密码

    private String nickname;// 发件人的昵称

    private static Logger log = LoggerFactory.getLogger(MailSender.class);

 

    /**

     * 有参构造器

     *

     * @param smtp

     */

    public MailSender(String smtp) {

        setSmtpHost(smtp);

        createMimeMessage();

    }

 

    /**

     * 设置邮件发送的SMTP主机

     *

     * @Date:2014年4月26日 上午10:20:34

     * @author

     * @param hostName

     *            SMTP 发送主机

     * @Description:

     * @return void

     */

    public void setSmtpHost(String hostName) {

        if (props == null)

            props = System.getProperties();

        props.put("mail.smtp.host", hostName);

        log.debug("set system properties success :mail.smtp.host= " + hostName);

 

    }

 

    /**

     * 创建邮件对象

     *

     * @Date:2014年4月26日 上午10:26:34

     * @author

     * @return

     * @Description:

     * @return boolean

     */

    public void createMimeMessage() {

        // 获得邮件会话对象

        session = Session.getDefaultInstance(props, null);

        // 创建MIME邮件对象

        mimeMsg = new MimeMessage(session);

        mp = new MimeMultipart();

        log.debug(" create session and mimeMessage success");

    }

 

    /**

     * 设置权限鉴定配置

     *

     * @Date:2014年4月26日 上午10:36:34

     * @author

     * @param need

     *            是否需要权限

     * @Description:

     * @return void

     */

    public void setNeedAuth(boolean need) {

        if (props == null)

            props = System.getProperties();

        if (need) {

            props.put("mail.smtp.auth", "true");

        } else {

            props.put("mail.smtp.auth", "false");

        }

        log.debug("set smtp auth success:mail.smtp.auth= " + need);

 

    }

 

    /**

     * 设置发送邮件的主题

     *

     * @Date:2014年4月26日 上午10:26:34

     * @author

     * @param subject

     *            邮件的主题

     * @throws UnsupportedEncodingException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void setSubject(String subject) throws UnsupportedEncodingException,

            MessagingException {

        mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));

        log.debug("set mail subject success, subject= " + subject);

 

    }

 

    /**

     *

     * @Date:2014年4月26日 上午10:28:34

     * @author

     * @param mailBody

     *            邮件的正文内容

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void setBody(String mailBody) throws MessagingException {

        BodyPart bp = new MimeBodyPart();

        bp.setContent("" + mailBody, "text/html;charset=utf-8");

        mp.addBodyPart(bp);

        log.debug("set mail body content success,mailBody= " + mailBody);

    }

 

    /**

     * 添加邮件附件

     *

     * @Date:2014年4月26日 上午10:30:40

     * @author

     * @param filePath

     *            文件绝对路径

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void addFileAffix(String filePath) throws MessagingException {

        BodyPart bp = new MimeBodyPart();

        FileDataSource fileds = new FileDataSource(filePath);

        bp.setDataHandler(new DataHandler(fileds));

        bp.setFileName(fileds.getName());

        mp.addBodyPart(bp);

        log.debug("mail add file success,filename= " + filePath);

    }

 

    /**

     * 设置发件人邮箱地址

     *

     * @Date:2014年4月26日 上午10:35:54

     * @author

     * @param sender

     *            发件人邮箱地址

     * @throws UnsupportedEncodingException

     * @throws AddressException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void setSender(String sender) throws UnsupportedEncodingException,

            AddressException, MessagingException {

        nickname = MimeUtility.encodeText(nickname, "utf-8", "B");

        mimeMsg.setFrom(new InternetAddress(nickname + " <" + sender + ">"));

        log.debug(" set mail sender and nickname success , sender= " + sender

                + ",nickname=" + nickname);

    }

 

    /**

     * 设置收件人邮箱地址

     *

     * @Date:2014年4月26日 上午10:41:06

     * @author

     * @param receiver

     *            收件人邮箱地址

     * @throws AddressException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void setReceiver(String receiver) throws AddressException,

            MessagingException {

        mimeMsg.setRecipients(Message.RecipientType.TO,

                InternetAddress.parse(receiver));

        log.debug("set mail receiver success,receiver = " + receiver);

    }

 

    /**

     * 设置抄送人的邮箱地址

     *

     * @Date:2014年4月26日 上午10:42:14

     * @author

     * @param copyto

     *            抄送人邮箱地址

     * @throws AddressException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void setCopyTo(String copyto) throws AddressException,

            MessagingException {

        mimeMsg.setRecipients(Message.RecipientType.CC,

                InternetAddress.parse(copyto));

        log.debug("set mail copyto receiver success,copyto = " + copyto);

    }

 

    /**

     * 设置发件人用户名密码进行发送邮件操作

     *

     * @Date:2014年4月26日 上午10:44:01

     * @author

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public void sendout() throws MessagingException {

        mimeMsg.setContent(mp);

        mimeMsg.saveChanges();

        Session mailSession = Session.getInstance(props, null);

        Transport transport = mailSession.getTransport("smtp");

        transport.connect((String) props.get("mail.smtp.host"), username,

                password);

        transport.sendMessage(mimeMsg,

                mimeMsg.getRecipients(Message.RecipientType.TO));

        transport.close();

        log.debug(" send mail success");

    }

 

    /**

     * 注入发件人用户名 ,密码 ,昵称

     *

     * @Date:2014年4月26日 上午10:50:12

     * @author

     * @param username

     *            发件人邮箱登录用户名

     * @param password

     *            发件人邮箱密码

     * @param nickname

     *            发件人显示的昵称

     * @Description:

     * @return void

     */

    public void setNamePass(String username, String password, String nickname) {

        this.username = username;

        this.password = password;

        this.nickname = nickname;

 

    }

 

}

3. [代码]邮件内容模板生产工厂类     

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

package com.common.util.mail;

 

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.io.StringWriter;

import java.io.Writer;

import java.util.HashMap;

import java.util.Map;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.TemplateException;

 

/**

 * 邮件内容模板生产工厂类

 *

 * @date 2014年4月26日 下午3:06:04

 * @author

 * @Description:

 * @project mailUtil

 */

public class TemplateFactory {

    // 日志记录对象

    private static Logger log = LoggerFactory.getLogger(TemplateFactory.class);

    // 模板文件路径

    private static String templatePath = "/template";

    // 模板文件内容编码

    private static final String ENCODING = "utf-8";

    // 模板生成配置

    private static Configuration conf = new Configuration();

    // 邮件模板缓存池

    private static Map<String, Template> tempMap = new HashMap<String, Template>();

    static {

        // 设置模板文件路径

        conf.setClassForTemplateLoading(TemplateFactory.class, templatePath);

    }

 

    /**

     * 通过模板文件名称获取指定模板

     *

     * @Date:2014年4月26日 下午3:09:05

     * @author

     * @param name

     *            模板文件名称

     * @return Template 模板对象

     * @throws IOException

     * @Description:

     * @return Template

     */

    private static Template getTemplateByName(String name) throws IOException {

        if (tempMap.containsKey(name)) {

            log.debug("the template is already exist in the map,template name :"

                    + name);

            // 缓存中有该模板直接返回

            return tempMap.get(name);

        }

        // 缓存中没有该模板时,生成新模板并放入缓存中

        Template temp = conf.getTemplate(name);

        tempMap.put(name, temp);

        log.debug("the template is not found  in the map,template name :"

                + name);

        return temp;

    }

 

    /**

     * 根据指定模板将内容输出到控制台

     *

     * @Date:2014年4月26日 下午3:14:18

     * @author

     * @param name

     *            模板文件名称

     * @param map

     *            与模板内容转换对象

     * @Description:

     * @return void

     */

    public static void outputToConsole(String name, Map<String, String> map) {

        try {

            // 通过Template可以将模板文件输出到相应的流

            Template temp = getTemplateByName(name);

            temp.setEncoding(ENCODING);

            temp.process(map, new PrintWriter(System.out));

        } catch (TemplateException e) {

            log.error(e.toString(), e);

        } catch (IOException e) {

            log.error(e.toString(), e);

        }

    }

 

    /**

     * 根据指定模板将内容直接输出到文件

     *

     * @Date:2014年4月26日 下午3:20:15

     * @author

     * @param name

     *            模板文件名称

     * @param map

     *            与模板内容转换对象

     * @param outFile

     *            输出的文件绝对路径

     * @Description:

     * @return void

     */

    public static void outputToFile(String name, Map<String, String> map,

            String outFile) {

        FileWriter out = null;

        try {

            out = new FileWriter(new File(outFile));

            Template temp = getTemplateByName(name);

            temp.setEncoding(ENCODING);

            temp.process(map, out);

        } catch (IOException e) {

            log.error(e.toString(), e);

        } catch (TemplateException e) {

            log.error(e.toString(), e);

        } finally {

            try {

                if (out != null)

                    out.close();

            } catch (IOException e) {

                log.error(e.toString(), e);

            }

        }

    }

 

    /**

     *

     * @Date:2014年4月26日 下午3:24:37

     * @author

     * @param name

     *            模板文件的名称

     * @param map

     *            与模板内容转换对象

     * @return

     * @throws IOException

     * @throws TemplateException

     * @Description:

     * @return String

     */

    public static String generateHtmlFromFtl(String name,

            Map<String, String> map) throws IOException, TemplateException {

        Writer out = new StringWriter(2048);

        Template temp = getTemplateByName(name);

        temp.setEncoding(ENCODING);

        temp.process(map, out);

        return out.toString();

    }

}

4. [代码]邮件发送工具类     

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

package com.common.util.mail;

 

import java.io.IOException;

import java.util.Map;

import javax.mail.MessagingException;

import freemarker.template.TemplateException;

 

/**

 * 邮件发送工具类

 *

 * @date 2014年4月26日 下午3:30:04

 * @author

 * @Description:

 * @project mailUtil

 */

public class MailUtil {

 

    /**

     * 根据模板名称查找模板,加载模板内容后发送邮件

     *

     * @Date:2014年4月26日 上午11:02:58

     * @author

     * @param receiver

     *            收件人地址

     * @param subject

     *            邮件主题

     * @param map

     *            邮件内容与模板内容转换对象

     * @param templateName

     *            模板文件名称

     * @throws IOException

     * @throws TemplateException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public static void sendMailByTemplate(String receiver, String subject,

            Map<String, String> map, String templateName) throws IOException,

            TemplateException, MessagingException {

        String maiBody = "";

        String server = ConfigLoader.getServer();

        String sender = ConfigLoader.getSender();

        String username = ConfigLoader.getUsername();

        String password = ConfigLoader.getPassword();

        String nickname = ConfigLoader.getNickname();

        MailSender mail = new MailSender(server);

        mail.setNeedAuth(true);

        mail.setNamePass(username, password, nickname);

        maiBody = TemplateFactory.generateHtmlFromFtl(templateName, map);

        mail.setSubject(subject);

        mail.setBody(maiBody);

        mail.setReceiver(receiver);

        mail.setSender(sender);

        mail.sendout();

    }

 

    /**

     * 根据模板名称查找模板,加载模板内容后发送邮件

     *

     * @Date:2014年4月26日 上午11:02:58

     * @author

     * @param receiver

     *            收件人地址

     * @param subject

     *            邮件主题

     * @param map

     *            邮件内容与模板内容转换对象

     * @param templateName

     *            模板文件名称

     * @throws IOException

     * @throws TemplateException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public static void sendMailAndFileByTemplate(String receiver,

            String subject, String filePath, Map<String, String> map,

            String templateName) throws IOException, TemplateException,

            MessagingException {

        String maiBody = "";

        String server = ConfigLoader.getServer();

        String sender = ConfigLoader.getSender();

        String username = ConfigLoader.getUsername();

        String password = ConfigLoader.getPassword();

        String nickname = ConfigLoader.getNickname();

        MailSender mail = new MailSender(server);

        mail.setNeedAuth(true);

        mail.setNamePass(username, password, nickname);

        maiBody = TemplateFactory.generateHtmlFromFtl(templateName, map);

        mail.setSubject(subject);

        mail.addFileAffix(filePath);

        mail.setBody(maiBody);

        mail.setReceiver(receiver);

        mail.setSender(sender);

        mail.sendout();

    }

 

    /**

     * 普通方式发送邮件内容

     *

     * @Date:2014年4月26日 下午1:20:47

     * @author

     * @param receiver

     *            收件人地址

     * @param subject

     *            邮件主题

     * @param maiBody

     *            邮件正文

     * @throws IOException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public static void sendMail(String receiver, String subject, String maiBody)

            throws IOException, MessagingException {

        String server = ConfigLoader.getServer();

        String sender = ConfigLoader.getSender();

        String username = ConfigLoader.getUsername();

        String password = ConfigLoader.getPassword();

        String nickname = ConfigLoader.getNickname();

        MailSender mail = new MailSender(server);

        mail.setNeedAuth(true);

        mail.setNamePass(username, password, nickname);

        mail.setSubject(subject);

        mail.setBody(maiBody);

        mail.setReceiver(receiver);

        mail.setSender(sender);

        mail.sendout();

    }

 

    /**

     * 普通方式发送邮件内容,并且附带文件附件

     *

     * @Date:2014年4月26日 下午1:20:47

     * @author

     * @param receiver

     *            收件人地址

     * @param subject

     *            邮件主题

     * @param filePath

     *            文件的绝对路径

     * @param maiBody

     *            邮件正文

     *

     * @throws IOException

     * @throws MessagingException

     * @Description:

     * @return void

     */

    public static void sendMailAndFile(String receiver, String subject,

            String filePath, String maiBody) throws IOException,

            MessagingException {

        String server = ConfigLoader.getServer();

        String sender = ConfigLoader.getSender();

        String username = ConfigLoader.getUsername();

        String password = ConfigLoader.getPassword();

        String nickname = ConfigLoader.getNickname();

        MailSender mail = new MailSender(server);

        mail.setNeedAuth(true);

        mail.setNamePass(username, password, nickname);

        mail.setSubject(subject);

        mail.setBody(maiBody);

        mail.addFileAffix(filePath);

        mail.setReceiver(receiver);

        mail.setSender(sender);

        mail.sendout();

    }

 

}

5. [代码]邮件工具测试类     

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

package com.mail.test;

 

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

 

import javax.mail.MessagingException;

 

import org.junit.Test;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.common.util.mail.MailUtil;

 

import freemarker.template.TemplateException;

 

/**

 * 邮件工具测试类

 *

 * @date 2014年4月26日 下午3:37:11

 * @author

 * @Description:

 * @project mailUtil

 */

public class MailUtilTest {

    private static Logger log = LoggerFactory.getLogger(MailUtilTest.class);

 

    @Test

    public void testMailTemplate() {

        String templateName = "template_1.ftl";

        Map<String, String> map = new HashMap<String, String>();

        map.put("content", "test");

        try {

            MailUtil.sendMailByTemplate("529352411@qq.com", "test", map,

                    templateName);

        } catch (IOException e) {

            log.error(e.toString(), e);

        } catch (TemplateException e) {

            log.error(e.toString(), e);

        } catch (MessagingException e) {

            log.error(e.toString(), e);

        }

    }

 

    @Test

    public void testMail() {

        try {

            MailUtil.sendMail("52935247119@qq.com", "test", "普通邮件");

        } catch (IOException e) {

            log.error(e.toString(), e);

        } catch (MessagingException e) {

            log.error(e.toString(), e);

        }

    }

 

    @Test

    public void testMailAndFile() {

        try {

            String filePath = "d:/data.zip";

            MailUtil.sendMailAndFile("52935211479@qq.com", "test", filePath,"普通邮件"

                    );

        } catch (IOException e) {

            log.error(e.toString(), e);

        } catch (MessagingException e) {

            log.error(e.toString(), e);

        }

    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Freemarker模板发送邮件,需要进行以下步骤: 1. 导入需要的依赖 在Maven项目中,需要在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> ``` 2. 编写Freemarker模板 比如我们可以编写一个简单的模板,如下: ``` <html> <body> <h1>Hello ${username}!</h1> <p>Here is your message:</p> <p>${message}</p> </body> </html> ``` 在模板中,我们可以使用Freemarker的语法来动态生成HTML内容。 3. 编写Java代码 我们可以编写一个名为`EmailService`的Java类来发送邮件。 首先,我们需要创建一个`VelocityEngine`对象,来加载Freemarker模板: ``` VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); ``` 然后,我们可以使用`VelocityEngine`对象来加载模板文件: ``` Template template = velocityEngine.getTemplate("email-template.vm"); ``` 接下来,我们需要创建一个`VelocityContext`对象,并将模板中需要填充的变量添加到该对象中: ``` VelocityContext context = new VelocityContext(); context.put("username", username); context.put("message", message); ``` 最后,我们可以使用`JavaMail`库来发送邮件: ``` Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromEmail, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromEmail)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); message.setSubject(subject); StringWriter writer = new StringWriter(); template.merge(context, writer); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(writer.toString(), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); ``` 在以上代码中,我们首先创建了一个`Properties`对象来配置邮件服务器的信息。然后,我们创建了一个`Session`对象,并使用`Authenticator`对象来进行SMTP认证。接着,我们创建了一个`MimeMessage`对象,并设置了邮件的发送者、接收者和主题。然后,我们将模板生成的HTML内容添加到`MimeBodyPart`对象中,最后将`MimeBodyPart`对象添加到`Multipart`对象中,并将`Multipart`对象设置为邮件的内容。最后,我们使用`Transport`对象的`send`方法来发送邮件。 这就是使用Freemarker模板发送邮件的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值