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
|
private static void send(
String smtpServer,
String encodingServer,
InternetAddress from,
InternetAddress[] toMails,
InternetAddress[] ccMails,
String subject,
String text,
List attachedFiles) throws MessagingException {
/**
* Encoding : Utilisation du system.getProperties. <br>
* A modifier si passage en JavaMail-1.3
* http://java.sun.com/products/javamail/JavaMail-1.3-changes.txt <br>
* 3. Add mail.mime.charset property (4377731) <br>
* ------------------------------------------- <br>
* The "mail.mime.charset" System property (NOTE: *not* Session
* property) names the default charset to be used by JavaMail. If not
* set, the standard J2SE "file.encoding" System property is used. This
* allows applications to specify a default character set for sending
* messages that's different than the character set used for files
* stored on the system. This is common on Japanese systems.
*/
Properties props = System.getProperties();
String encoding = props.getProperty("file.encoding");
props.setProperty("file.encoding", encodingServer);
try {
// -- Attaching to default Session, or we could start a new one --
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
// Create a new message
Message msg = new MimeMessage(session);
// Set the FROM and TO fields
msg.setFrom(from);
msg.setRecipients(Message.RecipientType.TO, toMails);
// -- We could include CC recipients too --
if (ccMails != null) {
msg.setRecipients(Message.RecipientType.CC, ccMails);
}
// Set the subject
if (subject != null) {
msg.setSubject(subject);
}
// Set some other header information
msg.setSentDate(new Date());
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
// Text
if ((text.toUpperCase().startsWith("<HTML"))
|| (text.toUpperCase().startsWith("<!"))) {
mbp1.setContent(text, "text/html");
} else {
mbp1.setText(text);
}
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
if (attachedFiles != null) {
for (Iterator iter = attachedFiles.iterator(); iter.hasNext();) {
// create the next message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the Multipart
String fileName = (String) iter.next();
FileDataSource fds = new FileDataSource(fileName);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(new java.io.File(fileName).getName());
mp.addBodyPart(mbp2);
}
}
// add the Multipart to the message
msg.setContent(mp);
// Send the message
Transport.send(msg);
} catch (MessagingException e)
{
throw e;
} finally {
props.setProperty("file.encoding", encoding);
} |
Partager