Envoi et lecture de mails (+authentification +ssl +pièces jointes +html +images)

Description

Gestion SSL et d'authentification (Fonctionne avec Gmail ;-)

- La classe MailSender permet d'envoyer des mails.
Les e-mails peuvent contenir
- du texte brut ;
- du texte au format html (avec possibilité d'intégrer des images);
- des pièces jointes
J'ai intégré deux exemples dans le main de MailSender.

- La classe MailReceiver permet de réceptionner des mails.
Un exemple basique est présent dans le main de MailReceiver.

ATTENTION: Ces Classes fonctionnent avec l'api JavaMail.
Il faut donc inclure les packages mail.jar ainsi que activation.jar
J'ai inclus ces .jar dans le zip

Source / Exemple :


/* 

  • MailSender
  • Created on 28 oct. 2005
  • @author Toon from insia
  • /
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 MailSender { 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; // Constructeur n°1: Connexion au serveur mail public MailSender(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); } else { // Connexion avec authentification _session = Session.getDefaultInstance(props, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); } } // Autres constructeurs public MailSender(final String host, final String userName, final String password, final boolean ssl) { this(host, DEFAULT_SMTP_PORT, userName, password, ssl); } public MailSender(final String host, final String userName, final String password) { this(host, DEFAULT_SMTP_PORT, userName, password, false); } public MailSender(final String host, final int port) { this(host, port, null, null, false); } public MailSender(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(); } // Exemples public static void main(final String[] args) throws UnsupportedEncodingException, IOException, MessagingException { // connexion au serveur de mail final MailSender mail1 = new MailSender("smtp.xxxxxx.xxx"); // Message simple : (from et to sont indispensables) final MailMessage msg = new MailMessage(); msg.setFrom("xxxxxx@xxxxxx.xxx"); msg.setTo("xxxxxx@xxxxxx.xxx"); msg.setCc("xxxxxx@xxxxxx.xxx"); msg.setSubject("sujet"); msg.setContent("corps du message", false); mail1.sendMessage(msg); // connexion à un autre serveur de mail // (l'activation du compte pop est nécessaire pour gmail) final MailSender mail2 = new MailSender("smtp.gmail.com", 465, "xxxxxx", "xxxxxx", true); // Message avec texte html + images incluses + pièces jointes msg.setFrom(new InternetAddress("martin@gmail.net", "Martin john")); msg.setTo("dupont@gmail.com"); msg.setCc( new InternetAddress[] { new InternetAddress("gaston@gmail.net", "Gaston lagaffe"), new InternetAddress("gilbert@gmail.net") } ); msg.setSubject("sujet"); msg.setContent("<p><h1>Salut</h1></p>" + "<p>Image 1:<img src=\"cid:image1.jpg\"></p>" + "<p>Image 2:<img src=\"cid:image2.jpg\"></p>" + "<p>Encore image 1:<img src=\"cid:image1.jpg\"></p>", true); msg.setAttachmentURL(new String[] { "c:\\toto.txt", "c:\\image1.jpg", "c:\\tata.txt", "c:\\image2.jpg" }); mail2.sendMessage(msg); } } ##################################################################################### /*
  • MailReceiver
  • Created on 28 oct. 2005
  • @author Toon from insia
  • /
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Security; import java.text.SimpleDateFormat; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; import javax.mail.URLName; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMultipart; public class MailReceiver { final private static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final private static int DEFAULT_POP_PORT = 110; final private static int DEFAULT_POP_SSL_PORT = 995; final private String _popHost; final private String _popPort; final private String _userName; final private String _password; final private Properties _props; final private Store _store; public MailReceiver(final String host, final String userName, final String password, final int port, final boolean ssl) throws NoSuchProviderException { _popHost = host; _popPort = String.valueOf(port); _userName = userName; _password = password; _props = new Properties(); if (ssl) { // Connection SSL Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); _props.put("mail.pop3.socketFactory.class", SSL_FACTORY); _props.put("mail.pop3.socketFactory.fallback", "false"); _props.put("mail.pop3.port", _popPort); _props.put("mail.pop3.socketFactory.port", _popPort); } final Session session = Session.getDefaultInstance(_props, null); final URLName urln = new URLName("pop3", host, port, null, userName, password); _store = session.getStore(urln); } public MailReceiver(final String host, final String userName, final String password, final boolean ssl) throws NoSuchProviderException { this(host, userName, password, (ssl ? DEFAULT_POP_SSL_PORT : DEFAULT_POP_PORT), ssl); } public MailReceiver(final String host, final String userName, final String password, final int port) throws NoSuchProviderException { this(host, userName, password, port, DEFAULT_POP_SSL_PORT == port); } public MailReceiver(final String host, final String userName, final String password) throws NoSuchProviderException { this(host, userName, password, DEFAULT_POP_PORT, false); } public MailMessage[] getMessages() throws UnsupportedEncodingException, IOException, MessagingException { MailMessage[] results = null; try { _store.connect(); final Folder inbox = _store.getFolder("INBOX"); try { inbox.open(Folder.READ_ONLY); final Message[] messages = inbox.getMessages(); results = new MailMessage[messages.length]; for (int i = 0; i < messages.length; ++i) results[i] = new MailMessage(messages[i]); } finally { inbox.close(false); } } finally { _store.close(); } return results; } public static void main(final String[] args) throws UnsupportedEncodingException, IOException, MessagingException { // Connexion final MailReceiver gmail = new MailReceiver("pop.xxxxxx.xxx", "xxxxxx", "xxxxxx"); // Réception final MailMessage[] messages = gmail.getMessages(); // Affichage final SimpleDateFormat datFormat = new SimpleDateFormat("'le' dd/MM/yyyy 'à' HH:mm"); for (int i = 0; i < messages.length; ++i) { System.out.print(datFormat.format(messages[i].getSendDate())); System.out.print(" De: " + messages[i].getFrom().getAddress()); System.out.print(" à: "); final InternetAddress[] to = messages[i].getTo(); for (int j = 0; j < to.length; ++j) System.out.print(to[i].getAddress() + (to.length - 1 != j ? ", " : "\n")); System.out.println(" - " + messages[i].getSubject() + "\n"); } } } ##################################################################################### /*
  • MailMessage
  • Created on 28 oct. 2005
  • @author Toon from insia
  • /
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Date; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; public final class MailMessage { private String _subject = ""; private Object _content = ""; private boolean _html = false; private InternetAddress _from = null; private InternetAddress[] _to = null; private InternetAddress[] _cc = null; private InternetAddress[] _bcc = null; private String[] _attachmentURL = null; private Date _sendDate = new Date(); private Date _receivedDate = null; private InternetAddress[] getAddress(final InternetAddress address) { return new InternetAddress[] { address }; } private InternetAddress[] getAddress(final String[] address) throws AddressException { final InternetAddress[] result = new InternetAddress[address.length]; for (int i = 0; i < address.length; ++i) result[i] = new InternetAddress(address[i]); return result; } private InternetAddress[] getAddress(final String address) throws AddressException { return new InternetAddress[] { new InternetAddress(address) }; } private InternetAddress[] getInternetAddress(final Address[] address) throws AddressException, UnsupportedEncodingException { if (null == address) return null; final InternetAddress[] result = new InternetAddress[address.length]; for (int i = 0; i < address.length; ++i) result[i] = new InternetAddress(decodeText(address[i].toString())); return result; } public MailMessage() { } public MailMessage(final Message msg) throws IOException, MessagingException { _from = getInternetAddress(msg.getFrom())[0]; _to = getInternetAddress(msg.getRecipients(Message.RecipientType.TO)); _cc = getInternetAddress(msg.getRecipients(Message.RecipientType.CC)); _subject = msg.getSubject(); _content = msg.getContent(); _sendDate = msg.getSentDate(); _receivedDate = msg.getReceivedDate(); } private static String decodeText(final String text) throws UnsupportedEncodingException { return null == text ? text : new String(text.getBytes("iso-8859-1")); } public void reset() { _subject = ""; _content = ""; _html = false; _from = null; _to = null; _cc = null; _bcc = null; _attachmentURL = null; } // Getters public InternetAddress getFrom() { return _from; } public InternetAddress[] getTo() { return _to; } public InternetAddress[] getCc() { return _cc; } public InternetAddress[] getBcc() { return _bcc; } public Object getContent() { return _content; } public String getSubject() { return _subject; } public String[] getAttachmentURL() { return _attachmentURL; } public boolean isHtml() { return _html; } public Date getSendDate() { return _sendDate; } // Setters public void setFrom(final InternetAddress from) { _from = from; } public void setFrom(final String from) throws AddressException { _from = new InternetAddress(from); } public void setTo(final InternetAddress[] to) { _to = to; } public void setTo(final InternetAddress to) { _to = getAddress(to); } public void setTo(final String[] to) throws AddressException { _to = getAddress(to); } public void setTo(final String to) throws AddressException { _to = getAddress(to); } public void setCc(final InternetAddress[] cc) { _cc = cc; } public void setCc(final InternetAddress cc) { _cc = getAddress(cc); } public void setCc(final String[] cc) throws AddressException { _cc = getAddress(cc); } public void setCc(final String cc) throws AddressException { _cc = getAddress(cc); } public void setBcc(final InternetAddress[] bcc) { _bcc = bcc; } public void setBcc(final InternetAddress bcc) { _bcc = getAddress(bcc); } public void setBcc(final String[] bcc) throws AddressException { _bcc = getAddress(bcc); } public void setBcc(final String bcc) throws AddressException { _bcc = getAddress(bcc); } public void setSubject(final String subject) { _subject = subject; } public void setContent(final String content, final boolean html) { _content = content; _html = html; } public void setAttachmentURL(final String[] attachmentURL) { _attachmentURL = attachmentURL; } public void setAttachmentURL(final String attachmentURL) { _attachmentURL = new String[] { attachmentURL }; } }

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.