Subversion Repositories SmartDukaan

Rev

Rev 5138 | Rev 8675 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2822 chandransh 1
package in.shop2020.utils;
2
 
4827 mandeep.dh 3
import java.io.File;
2822 chandransh 4
import java.security.Security;
5138 mandeep.dh 5
import java.util.ArrayList;
6
import java.util.HashMap;
4827 mandeep.dh 7
import java.util.List;
5138 mandeep.dh 8
import java.util.Map;
2822 chandransh 9
import java.util.Properties;
10
 
11
import javax.activation.DataHandler;
12
import javax.activation.DataSource;
13
import javax.activation.FileDataSource;
14
import javax.mail.Message;
15
import javax.mail.MessagingException;
16
import javax.mail.Multipart;
17
import javax.mail.PasswordAuthentication;
18
import javax.mail.Session;
19
import javax.mail.Transport;
4827 mandeep.dh 20
import javax.mail.internet.AddressException;
2822 chandransh 21
import javax.mail.internet.InternetAddress;
22
import javax.mail.internet.MimeBodyPart;
23
import javax.mail.internet.MimeMessage;
24
import javax.mail.internet.MimeMultipart;
5128 amit.gupta 25
import javax.mail.util.ByteArrayDataSource;
2822 chandransh 26
 
27
public class GmailUtils {
28
 
29
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
30
    private static final String SMTP_PORT = "465";
31
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
32
 
33
    public GmailUtils(){
34
    }
35
 
36
    public void sendSSLMessage(String recipients[], String subject, String message, final String from, final String password, String filename) throws MessagingException {
5138 mandeep.dh 37
        try {
38
            Message msg = prepareMessage(recipients, subject, from, password);
39
            //Create the multi-part object to hold the text and attachment parts
40
            Multipart multipart = new MimeMultipart();
41
            // create the message part 
42
            MimeBodyPart messageBodyPart = new MimeBodyPart();
43
            //Part 1: Text message
44
            messageBodyPart.setText(message);
45
            multipart.addBodyPart(messageBodyPart);
46
            //Part 2: Attachment
47
            messageBodyPart = new MimeBodyPart();
48
            DataSource source = new FileDataSource(filename);
49
            messageBodyPart.setDataHandler(new DataHandler(source));
50
            String[] names = filename.split("/");
51
            messageBodyPart.setFileName(names[names.length - 1]);
52
            multipart.addBodyPart(messageBodyPart);
53
            // Put parts in message
54
            msg.setContent(multipart);
55
            Transport.send(msg);
56
        } catch (Exception e) {
57
            // If there is any error with normal mail sending, try diving receipients across domains
58
            if (hasMultipleDomains(recipients)) {
59
                for (List<String> subReceipients : getReceipientsPerDomain(recipients).values()) {
60
                    sendSSLMessage(subReceipients.toArray(new String[0]), subject, message, from, password, filename);
61
                }
4827 mandeep.dh 62
 
5138 mandeep.dh 63
                return;
64
            }
65
 
66
            throw new MessagingException(e.getMessage(), e);
67
        }
68
    }
4827 mandeep.dh 69
 
5138 mandeep.dh 70
    /**
71
     * @param recipients
72
     * @return
73
     */
74
    private Map<String, List<String>> getReceipientsPerDomain(String[] recipients) {
75
        Map<String, List<String>> result = new HashMap<String, List<String>>();
76
        for (String recipient : recipients) {
77
            String domain = extractDomainFromEmailAddress(recipient);
4827 mandeep.dh 78
 
5138 mandeep.dh 79
            if (!result.containsKey(domain)) {
80
                result.put(domain, new ArrayList<String>());
81
            }
82
 
83
            result.get(domain).add(recipient);
84
        }
85
 
86
        return result;
4827 mandeep.dh 87
    }
88
 
5138 mandeep.dh 89
    /**
90
     * @param recipients
91
     * @return
92
     */
93
    private boolean hasMultipleDomains(String[] recipients) {
94
        String domain = extractDomainFromEmailAddress(recipients[0]);
95
        for (String recipient : recipients) {
96
            if (!domain.equals(extractDomainFromEmailAddress(recipient))) {
97
                return true;
98
            }
99
        }
100
 
101
        return false;
102
    }
103
 
104
    private String extractDomainFromEmailAddress(String recipient) {
105
        return recipient.split("@")[1];
106
    }
107
 
4827 mandeep.dh 108
    public void sendSSLMessage(String recipients[], String subject, String message, final String from, final String password, List<File> files) throws MessagingException {
5138 mandeep.dh 109
        try {
110
            Message msg = prepareMessage(recipients, subject, from, password);
111
 
112
            //Create the multi-part object to hold the text and attachment parts
113
            Multipart multipart = new MimeMultipart();
114
 
115
            // create the message part 
116
            MimeBodyPart messageBodyPart = new MimeBodyPart();
117
            //Part 1: Text message
118
            messageBodyPart.setText(message);
119
            multipart.addBodyPart(messageBodyPart);
4827 mandeep.dh 120
 
5138 mandeep.dh 121
            //Part 2: Attachment
122
            for (File file : files) {
123
                DataSource source = new FileDataSource(file);
124
                String[] names = file.getAbsolutePath().split("/");
125
                messageBodyPart = new MimeBodyPart();
126
                messageBodyPart.setDataHandler(new DataHandler(source));
127
                messageBodyPart.setFileName(names[names.length - 1]);
128
                multipart.addBodyPart(messageBodyPart);
129
            }
130
 
131
            // Put parts in message
132
            msg.setContent(multipart);
133
            Transport.send(msg);
134
        } catch (Exception e) {
135
            // If there is any error with normal mail sending, try diving receipients across domains
136
            if (hasMultipleDomains(recipients)) {
137
                for (List<String> subReceipients : getReceipientsPerDomain(recipients).values()) {
138
                    sendSSLMessage(subReceipients.toArray(new String[0]), subject, message, from, password, files);
139
                }
140
 
141
                return;
142
            }
143
 
144
            throw new MessagingException(e.getMessage(), e);
4827 mandeep.dh 145
        }
146
    }
147
 
5138 mandeep.dh 148
    @SuppressWarnings("restriction")
4827 mandeep.dh 149
    private Message prepareMessage(String[] recipients, String subject,
150
            final String from, final String password) throws AddressException,
151
            MessagingException {
2822 chandransh 152
        boolean debug = true;
153
 
154
        Properties props = new Properties();
155
        props.put("mail.smtp.host", SMTP_HOST_NAME);
156
        props.put("mail.smtp.auth", "true");
157
        props.put("mail.debug", "true");
158
        props.put("mail.smtp.port", SMTP_PORT);
159
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
160
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
161
        props.put("mail.smtp.socketFactory.fallback", "false");
162
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
163
 
164
        Session session = Session.getDefaultInstance(props,
165
                new javax.mail.Authenticator() {
166
 
167
                    protected PasswordAuthentication getPasswordAuthentication() {
168
                        return new PasswordAuthentication(from, password);
169
                    }
170
                });
171
 
172
        session.setDebug(debug);
173
 
174
        Message msg = new MimeMessage(session);
175
 
176
        //Set the from address
177
        InternetAddress addressFrom = new InternetAddress(from);
178
        msg.setFrom(addressFrom);
179
 
180
        //Set the recipients
181
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
182
        for (int i = 0; i < recipients.length; i++) {
183
            addressTo[i] = new InternetAddress(recipients[i]);
184
        }
185
        msg.setRecipients(Message.RecipientType.TO, addressTo);
186
 
187
        //Setting the Subject
188
        msg.setSubject(subject);
4827 mandeep.dh 189
        return msg;
2822 chandransh 190
    }
191
 
192
    public static void main(String args[]) throws Exception {
5138 mandeep.dh 193
        String[] sendTo = { "mandeep.dhir@shop2020.in", "mandeep.dhir@gmail.com", "mandeepcse07@yahoo.co.in", "anupam.singh@shop2020.in" };
194
        String emailSubjectTxt = "Another test from gmail";
2822 chandransh 195
        String emailMsgTxt = "Test Message Contents";
5138 mandeep.dh 196
        String emailFromAddress = "mandeep.dhir@shop2020.in";
197
        String password = "";
198
        String filename = "/home/mandeep/virtual_warehouse.sql";
199
 
2822 chandransh 200
        GmailUtils utils = new GmailUtils();
201
        utils.sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress, password, filename);
202
        System.out.println("Sucessfully Sent mail to All Users");
203
    }
204
}