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
package com.vci.server.base.mail;
 
import java.util.Locale;
import java.util.Properties;
 
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
 
import com.vci.common.exception.LocaleCommonDisplay;
import com.vci.corba.common.VCIError;
 
public class EmailSender implements IEmailSender{
    
    private static EmailSender emailSender = null;
    
    public static EmailSender getInstance() {
        if (emailSender == null) {
            emailSender = new EmailSender();
        }
        
        return emailSender;
    }
 
    @Override
    public boolean sendEmail(MailObject obj) throws VCIError {
        boolean rs = false;
        try {
            EmaiAuthenticator auth = new EmaiAuthenticator();
            Properties pros = EmailProperties.getProperties(); 
            Session session = Session.getInstance(pros, auth);  
            MailMessage mailMessage = new MailMessage();
            Message message = mailMessage.getMailMessage(session, obj);
            Transport.send(message);     
            rs = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new VCIError("", new String[]{LocaleCommonDisplay.getI18nString("700001", "RMIPMail",Locale.getDefault())});
        }
        
        return rs;
    }
    
    /**
     * 判断当前用户名密码是否正确
     * @param host, smtp服务器
     * @param userName, 用户名
     * @param password, 密码
     * @return
     */
    @Override
    public boolean verifyUserHasAuth(String host, String userName, String password) {
        boolean isHas = false;
        Properties props = new Properties(); 
        props.put("mail.smtp.host", host);//指定SMTP服务器 
        props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证 
        try  { 
            Session mailSession = Session.getInstance(props); 
            mailSession.setDebug(true);//是否在控制台显示debug信息 
 
            Transport transport = mailSession.getTransport("smtp"); 
            transport.connect(host, userName, password); 
            transport.close(); 
            isHas = true;
        } catch (Exception e)  { 
            e.printStackTrace();
            //System.out.println(e); 
        } 
        
        return isHas;
    }
    
    public static void main(String[] args) throws VCIError {
        EmailSender sender = EmailSender.getInstance();
        MailObject obj = new MailObject();
        obj.setMailFrom("liucq@vci-tech.com");
        obj.setSubject("我的测试邮件题目");
        obj.setText("请点击链接: www.163.com  ss");
        String[] mailTos = new String[1];
        mailTos[0] = "liucq@vci-tech.com";
        obj.setMailTos(mailTos);
        sender.sendEmail(obj);
    }
}