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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
|
package test.sendmail;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
public class Envoi2 {
final private static String CHARSET = "charset=ISO-8859-1";
final private static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
final private static int DEFAULT_SMTP_PORT = 25;
final private Session _session;
// Exemples
public static void main(String args[]) throws UnsupportedEncodingException, IOException, MessagingException {
// Message simple : (from et to sont indispensables)
final MailMessage msg = new MailMessage();
// connexion à un autre serveur de mail
// (l'activation du compte pop est nécessaire pour gmail)
final Envoi2 mail2 = new Envoi2("smtp.gmail.com", 465, "addresseFrom", "motDePasse", true);
// Message avec texte html + images incluses + pièces jointes
msg.setFrom(new InternetAddress("addresseFrom@gmail.com", "Nom..."));
msg.setTo("adresseTo@gmail.com");
msg.setCc(
new InternetAddress[] {
new InternetAddress("AddresseCopie1@bbb.ccc", "NOM..."),
new InternetAddress("AddresseCopie2@ddd.eee", "NOM...")
}
);
msg.setSubject("sujet");
String msgContent = "<p><h3>Salut</h3></p><br><br>Si vous recevez ce mail, " +
"c'est que le mailing avec java fonctionne" +
", et que ce programme vous permettera d\'envoyer meme des fichiers joint" +
"<br>Cordialment,";
msg.setContent(msgContent, true);
mail2.sendMessage(msg);
System.out.print("Votre message a été bien transmis");
}
// Constructeur n°1: Connexion au serveur mail
public Envoi2(final String host, final int port, final String userName,
final String password, final boolean ssl) {
final String strPort = String.valueOf(port);
final Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", strPort);
if (ssl) {
// Connection SSL
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", strPort);
}
if (null == userName || null == password) {
_session = Session.getDefaultInstance(props, null);
_session.setDebug(true);
} else {
// Connexion avec authentification
_session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
}
}
// Autres constructeurs
public Envoi2(final String host, final String userName,
final String password, final boolean ssl) {
this(host, DEFAULT_SMTP_PORT, userName, password, ssl);
}
public Envoi2(final String host, final String userName,
final String password) {
this(host, DEFAULT_SMTP_PORT, userName, password, false);
}
public Envoi2(final String host, final int port) {
this(host, port, null, null, false);
}
public Envoi2(final String host) {
this(host, DEFAULT_SMTP_PORT, null, null, false);
}
// Convertit un texte au format html en texte brut
private static final String HtmlToText(final String s) {
final HTMLEditorKit kit = new HTMLEditorKit();
final Document doc = kit.createDefaultDocument();
try {
kit.read(new StringReader(s), doc, 0);
return doc.getText(0, doc.getLength()).trim();
} catch (final IOException ioe) {
return s;
} catch (final BadLocationException ble) {
return s;
}
}
// Défini les fichiers à joindre
private void setAttachmentPart(final String[] attachmentPaths,
final MimeMultipart related, final MimeMultipart attachment,
final String body, final boolean htmlText)
throws MessagingException {
for (int i = 0; i < attachmentPaths.length; ++i) {
// Création du fichier à inclure
final MimeBodyPart messageFilePart = new MimeBodyPart();
final DataSource source = new FileDataSource(attachmentPaths[i]);
final String fileName = source.getName();
messageFilePart.setDataHandler(new DataHandler(source));
messageFilePart.setFileName(fileName);
// Image à inclure dans un texte au format HTML ou pièce jointe
if (htmlText && null != body && body.matches(
".*<img[^>]*src=[\"|']?cid:([\"|']?" + fileName + "[\"|']?)[^>]*>.*")) {
// " <-- pour éviter une coloration syntaxique désastreuse...
messageFilePart.setDisposition("inline");
messageFilePart.setHeader("Content-ID", '<' + fileName + '>');
related.addBodyPart(messageFilePart);
} else {
messageFilePart.setDisposition("attachment");
attachment.addBodyPart(messageFilePart);
}
}
}
// Texte alternatif = texte + texte html
private void setHtmlText(final MimeMultipart related,
final MimeMultipart alternative, final String body)
throws MessagingException {
// Plain text
final BodyPart plainText = new MimeBodyPart();
plainText.setContent(HtmlToText(body), "text/plain; " + CHARSET);
alternative.addBodyPart(plainText);
// Html text ou Html text + images incluses
final BodyPart htmlText = new MimeBodyPart();
htmlText.setContent(body, "text/html; " + CHARSET);
if (0 != related.getCount()) {
related.addBodyPart(htmlText, 0);
final MimeBodyPart tmp = new MimeBodyPart();
tmp.setContent(related);
alternative.addBodyPart(tmp);
} else {
alternative.addBodyPart(htmlText);
}
}
// Définition du corps de l'e-mail
private void setContent(final Message message,
final MimeMultipart alternative, final MimeMultipart attachment,
final String body)
throws MessagingException {
if (0 != attachment.getCount()) {
// Contenu mixte: Pièces jointes + texte
if (0 != alternative.getCount() || null != body) {
// Texte alternatif = texte + texte html
final MimeBodyPart tmp = new MimeBodyPart();
tmp.setContent(alternative);
attachment.addBodyPart(tmp, 0);
} else {
// Juste du texte
final BodyPart plainText = new MimeBodyPart();
plainText.setContent(body, "text/plain; " + CHARSET);
attachment.addBodyPart(plainText, 0);
}
message.setContent(attachment);
} else {
// Juste un message texte
if (0 != alternative.getCount()) {
// Texte alternatif = texte + texte html
message.setContent(alternative);
}else {
// Texte
message.setText(body);
}
}
}
// Prototype n°1: Envoi de message avec pièce jointe
public void sendMessage(final MailMessage mailMsg)
throws MessagingException {
final Message message = new MimeMessage(_session);
// Subect
message.setSubject(mailMsg.getSubject());
// Expéditeur
message.setFrom(mailMsg.getFrom());
// Destinataires
message.setRecipients(Message.RecipientType.TO, mailMsg.getTo());
message.setRecipients(Message.RecipientType.CC, mailMsg.getCc());
message.setRecipients(Message.RecipientType.BCC, mailMsg.getBcc());
// Contenu + pièces jointes + images
final MimeMultipart related = new MimeMultipart("related");
final MimeMultipart attachment = new MimeMultipart("mixed");
final MimeMultipart alternative = new MimeMultipart("alternative");
final String[] attachments = mailMsg.getAttachmentURL();
final String body = (String) mailMsg.getContent();
final boolean html = mailMsg.isHtml();
if (null != attachments)
setAttachmentPart(attachments, related, attachment, body, html);
if (html && null != body)
setHtmlText(related, alternative, body);
setContent(message, alternative, attachment, body);
// Date d'envoi
message.setSentDate(mailMsg.getSendDate());
// Envoi
Transport.send(message);
// Réinitialise le message
mailMsg.reset();
}
} |
Partager