使用Spring发送邮件

来源:互联网 发布:sqlserver最新版本 编辑:程序博客网 时间:2024/06/05 05:11

1. [代码]properties 文件     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#配置服务器邮件账号信息
#服务器
mail.smtp.host=smtp.xxx.com
#是否需要验证密码
mail.smtp.auth=true
#超时时间
mail.smtp.timeout=25000
#发件人信箱
mail.smtp.from=xxx@163.com
#用户名
mail.smtp.username=xxx@163.com
#密码
mail.smtp.password=123456

2. [代码]配置 applicationContext.xml     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    <!-- in-memory database and a datasource -->
    <beanid="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="classpath:jdbc.properties"/>
<!-- 配置邮件 senderbean -->
<beanid="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <propertyname="host"value="${mail.smtp.host}"></property>
    <propertyname="javaMailProperties">
        <props>
            <propkey="mail.smtp.auth">${mail.smtp.auth}</prop>
            <propkey="mail.smtp.timeout">${mail.smtp.timeout}</prop>      
        </props>
    </property>
    <propertyname="username"value="${mail.smtp.username}"></property>
    <propertyname="password"value="${mail.smtp.password}"></property>
</bean>

3. [代码]编写 ACTION 代码,实现邮件发送功能,这里还附加了一个附件     

?
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
/**
 ********************************************************************************************
 * @ClassName: ForcastAction
 * @Description: TODO
 * @author ZhouQian
 * @date 2014-6-11-上午11:00:34
 ********************************************************************************************
 */
publicclass ForcastAction extendsActionSupport implementsServletRequestAware, ServletResponseAware, SessionAware {
    privatestatic final long serialVersionUID = 1L;
    privateHttpServletRequest request;
    privateHttpServletResponse response;
    // struts mapsession ,key value
    privateMap<String, Object> session;
 
    // 邮件发送器
    privateJavaMailSenderImpl mailSender;
    // 设定上传文件路径
    privatestatic final String FOLDER_NAME = "/upload/";
 
    // 上传的附件和附件名称
    privateFile[] attachment;
    privateString[] attachmentFileName;
 
    /**
     * 邮件发送 接口用于向测试用户发送邮件 后期可能采用定时器进行邮件发送
     */
    publicvoid sendEmail() {
        // 邮件POJO 对象
        MailPojo mailPojo = newMailPojo();
        MimeMessage m = mailSender.createMimeMessage();
         
        // 构造附件
        String path = "jsp/theme/analyser/hero.html";
        path = request.getSession().getServletContext().getRealPath("/") + path;
        attachment = newFile[1];
        attachment[0] = newFile(path);
        attachmentFileName = newString[1];
        attachmentFileName[0] = "hero.html";
        try{
            MimeMessageHelper helper = newMimeMessageHelper(m, true,"UTF-8");
            // 设置收件人
            helper.setTo("xxx@163.com");
            // 设置抄送
//          helper.setCc("");
            // 设置发件人
            helper.setFrom("xxx@163.com");
            // 设置暗送
//          helper.setBcc("");
            // 设置主题
            helper.setSubject("测试邮件!");
            // 设置 HTML 内容
            helper.setText("这只是一封测试邮件!如果你收到的话说明我已经发送成功了!");
 
            // 保存附件,这里做一个 copy 只是为了防止上传文件丢失
            attachment = saveFiles(attachment, attachmentFileName);
            for(inti = 0; attachment != null&& i < attachment.length; i++) {
                File file = attachment[i];
                // 附件源
                FileSystemResource resource = newFileSystemResource(file);
                helper.addAttachment(attachmentFileName[i], resource);
                 
                // mail 对象填充
                AttachmentPojo attachmentPojo = newAttachmentPojo();
                attachmentPojo.setFilename(attachmentFileName[i]);
                attachmentPojo.setFilepath(file.getAbsolutePath());
                mailPojo.getAttachmentPojos().add(attachmentPojo);
            }
 
            // 进行邮件发送和邮件持久类的状态设定z
            mailSender.send(m);
            mailPojo.setSent(true);
            System.out.println("邮件发送成功!");
             
        }catch(Exception e) {
            e.printStackTrace();
            mailPojo.setSent(false);
            // TODO: handle exception
        }
//      dao.create(mail) 进行持久化,如果有这一步的话
    }
 
    /**
     * struts 2 会将文件自动上传到临时文件夹中,Action运行完毕后临时文件会被自动删除 因此需要将文件复制到 /upload 文件夹下
     *
     * @param files
     * @param names
     * @return
     */
    publicFile[] saveFiles(File[] files, String[] names) {
        if(files == null)
            returnnull;
        File root = newFile(ServletActionContext.getServletContext().getRealPath(FOLDER_NAME));
        File[] destinies = newFile[files.length];
        for(inti = 0; i < files.length; i++) {
            File file = files[i];
            File destiny = newFile(root, names[i]);
            destinies[i] = destiny;
            copyFile(file, destiny);
        }
        returndestinies;
    }
 
    /**
     * 复制单个文件
     *
     * @param from
     * @param to
     */
    publicvoid copyFile(File from, File to) {
        InputStream ins = null;
        OutputStream ous = null;
        try{
            // 创建所有上级文件夹
            to.getParentFile().mkdirs();
            ins = newFileInputStream(from);
            ous = newFileOutputStream(to);
            byte[] b = newbyte[1024];
            intlen;
            while((len = ins.read(b)) != -1) {
                ous.write(b,0, len);
            }
        }catch(Exception e) {
            // TODO: handle exception
        }finally{
            if(ous != null)
                try{
                    ous.close();
                }catch(Exception e) {
                    e.printStackTrace();
                }
            if(ins != null)
                try{
                    ins.close();
                }catch(Exception e) {
                    e.printStackTrace();
                }
        }
    }
 
    publicvoid setServletResponse(HttpServletResponse httpservletresponse) {
        this.response = httpservletresponse;
    }
 
    publicvoid setServletRequest(HttpServletRequest httpservletrequest) {
        this.request = httpservletrequest;
    }
 
    publicvoid setSession(Map<String, Object> session) {
        this.session = session;
    }
 
    publicJavaMailSenderImpl getMailSender() {
        returnmailSender;
    }
 
    publicvoid setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }
 
    publicFile[] getAttachment() {
        returnattachment;
    }
 
    publicvoid setAttachment(File[] attachment) {
        this.attachment = attachment;
    }
 
    publicString[] getAttachmentFileName() {
        returnattachmentFileName;
    }
 
    publicvoid setAttachmentFileName(String[] attachmentFileName) {
        this.attachmentFileName = attachmentFileName;
    }
 
}
原创粉丝点击