Total Pageviews

2016/07/08

[JavaMail] How to send email via Microsoft Exchange Server?

Problem
I am using JavaMail to write program to send email via Microsoft Exchange Server. How to do it?

How-to
The sample code looks like:
 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 albert.practice.mail;

import java.io.File;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import lombok.extern.slf4j.Slf4j;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import albert.practice.mail.params.EmailParams;

@Slf4j
public class ExchangeServerMailTest {

    public static void main(String[] args) {
        // set email parameters
        EmailParams params = new EmailParams();
        params.setReceiverEmail("email address");
        params.setSubject("測試一下");
        params.setContent("測試測試測試測試");

        // call sendMail API
        new ExchangeServerMailTest().sendMail(params);
    }

    public void sendMail(EmailParams params) {
        JavaMailSenderImpl sender = getJavaMailSender();
        MimeMessage message = sender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(params.getReceiverEmail());
            helper.setFrom("email address");
            helper.setSubject(params.getSubject());
            helper.setText(params.getContent(), false);

            // set attachment
            FileSystemResource attachment = new FileSystemResource(new File(
                    "D:\\dropbox\\退匯明細表.pdf"));
            helper.addAttachment("退匯明細表.pdf", attachment);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        sender.send(message);

        log.debug("mail sent..");
    }

    private JavaMailSenderImpl getJavaMailSender() {
        Properties props = new Properties();
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.ssl.trust", "*");

        // mail server configuration
        String host = "your smtp";
        int port = 25;
        String userName = "your user name";
        String password = "your password";

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setJavaMailProperties(props);
        sender.setHost(host);
        sender.setPort(port);
        sender.setUsername(userName);
        sender.setPassword(password);
        sender.setDefaultEncoding("UTF-8");

        return sender;
    }

}




No comments: