Subversion Repositories SmartDukaan

Rev

Rev 5140 | Rev 9703 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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