Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

ENVOI ET LECTURE DE MAILS (+AUTHENTIFICATION +SSL +PIÈCES JOINTES +HTML +IMAGES)


Information sur la source

Catégorie :Application Classé sous : mails, envoie, lecture, html, ssl Niveau : Initié Date de création : 30/09/2005 Date de mise à jour : 13/10/2005 13:48:34 Vu / téléchargé: 16 309 / 2 828

Note :
10 / 10 - par 3 personnes
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (24)
Ajouter un commentaire et/ou une note

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

  • /*
  • * 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 };
  • }
  • }
/* 
 * 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 };
    }

}

Fichier Zip

Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

Historique

02 octobre 2005 02:13:48 :
La classe MailSender gère maintenant le texte au format html ainsi que le la possibilité d'inclure des images dans un texte html.
02 octobre 2005 02:27:17 :
La coloration syntaxique n'étant pas encore tout à fait au point, j'ai du faire une modif...
02 octobre 2005 02:32:32 :
Toujours la coloration syntaxique...
13 octobre 2005 13:33:55 :
Réorganisation des classes, ajout de la classe MailMessage.
13 octobre 2005 13:43:16 :
&#9786;
13 octobre 2005 13:48:34 :
Ajout d'un zip

Commentaires et avis

signaler à un administrateur
Commentaire de abdoo05 le 25/11/2005 09:08:26

salut,
j'ai déja les deux package mail.jar et activation.jar et je travail avec Jbuilder 2005,mais le probléme est que je n'ai pas arriver à les installer..
alors si tu pourra m'aider et merci d'avance

signaler à un administrateur
Commentaire de tULIPOs le 26/02/2006 22:52:36

salut
tres cool ton prog mais le probléme et que je n'arrive pas a le faire marché meme sur gmail, voila l'exception que g:
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)
at javax.mail.Service.connect(Service.java:258)
at javax.mail.Service.connect(Service.java:137)

at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at MailSender.sendMessage(MailSender.java:205)
at MailSender.main(MailSender.java:249)

stp si t'as une idée sur le probléme( smtp par exemple ) n'hesite pas a m'aider, merci d'avance :)

signaler à un administrateur
Commentaire de tarzent le 10/05/2006 19:35:27

As-tu pensé à activer le protocole POP dans gmail?

signaler à un administrateur
Commentaire de djxtc le 26/07/2006 12:22:24

A part un i à remplacer par un j dans le main :
System.out.print(to[i].getAddress() +
à remplacer par
System.out.print(to[j].getAddress() +
sinon ca marche impec (je n'ai testé que la réception des mails), avec ou sans le ssl...

Du très bon boulot !

signaler à un administrateur
Commentaire de John_Doe_88 le 07/11/2006 15:24:34

Salut,

En ce moment je prog un webmail dans le meme genre.
Je cherche à extraire des pièces jointes des mails recus... Tu n'aurais pas fait ça par hasard ?

@+

JohnDoe

signaler à un administrateur
Commentaire de Berty2000 le 15/11/2006 01:16:24

j'obtiens cette erreur :

nested exception is:
class com.sun.mail.smtp.SMTPAddressFailedException: 550 No SMTP service for unauthorized users



J'ai pourtant bien defini le login et mot de passe dans le constructeur...

???

signaler à un administrateur
Commentaire de John_Doe_88 le 15/11/2006 09:35:37

A mon avis tu n'as pas de compte sur le SMTP que tu utilise. Il faut que ton adresse mail corresponde au serveur SMTP pour que tu aie le droit d'envoyer des mails par ce serveur SMTP.

Il ne suffit pas de définir les login et mot de passe, il faut aussi définir les serveurs d'envoi (pop ou imap) et de réception (smtp).

signaler à un administrateur
Commentaire de capoueidiablo le 20/11/2006 23:10:21

Tiens, un collègue de l'insia :)

signaler à un administrateur
Commentaire de freyssenonlio le 24/01/2007 15:18:43

Bravo !
Ca fait plus d'une demi journée que je cherchais à développer un code dans le genre à partir de javamail ! Et à cause de gmail rien ne marchait jamais ... et avec ton script rien que du bonheur ! :)

Juste un petit hic ... tout marche très bien sauf que l'on n'a me semble t il pas accès au corps du message ??? Comment pourrais je le récupérer ? As tu une idée ?

En tout cas merci beaucoup pour ces fonctions bien utiles et documentées

signaler à un administrateur
Commentaire de freyssenonlio le 24/01/2007 16:29:19

Après quelques recherches voici la solution que j'ai mis en place pour obtenir le contenu d'un message. J'ai remplacé

[code]
results = new MailMessage[messages.length];
for (int i = 0; i < messages.length; ++i){
results[i] = new MailMessage(messages[i]);
[/code]

par
[code]
results = new MailMessage[messages.length];
for (int i = 0; i < messages.length; ++i){
MimeMultipart contenu=(MimeMultipart) messages[i].getContent();
String messageContenu = (String) contenu.getBodyPart(1).getContent();
results[i] = new MailMessage(messages[i], messageContenu);
[/code]

Ensuite dans la classe MailMessage on rajoute un constructeur
[code]
// surcharge permettant de placer le contenu du message directement dans la valeur et non pas un mime inexploitable
    public MailMessage(final Message msg, String contenu)
    throws IOException, MessagingException {