begin process at 2010 03 22 09:26:39
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Application

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

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


 Information sur la source

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

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
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é :20 580 / 3 176

Auteur : tarzent

Ecrire un message privé
Commentaire sur cette source (25)
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

Les Membres Club peuvent 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

 Sources du même auteur

Source avec Zip ZIPPER / DÉZIPPER UN FICHIER, UN DOSSIER
JCALENDAR INTERNATIONALISÉ
RTF TO HTML

 Sources de la même categorie

Source avec Zip Source avec une capture SITE DES ANNONCES EN J2EE par TUIRIK
Source avec Zip Source avec une capture BANANA SPLIT par roiDesBranleurs
Source avec une capture ENVOIE DES SMS VIA LES COMMANDES AT par ingenioura
Source avec Zip ANALYSEUR DE PROXY IRC ET HTTP AVEC UNE INTERFACE GRAPHIQUE par sisisousou
Source avec Zip Source avec une capture "PROGRAMMEUR", EST UN PROGRAMME QUI PERMET DE TAPER QUELQUE ... par edouard333

 Sources en rapport avec celle ci

Source avec Zip JAVA SERVER PAGE par pasteure
Source avec Zip LECTURE DE CAPTCHA par coucou747
ENCODING A STRING USING HTML ENTITIES par futer
SUPPRIMER LES BALISES D'UN FICHIER HTML par AlexN
Source avec Zip PARSEUR STRING/HTML HTML/STRING par rem02

Commentaires et avis

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

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 :)

Commentaire de tarzent le 10/05/2006 19:35:27

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

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 !

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

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...

???

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).

Commentaire de capoueidiablo le 20/11/2006 23:10:21

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

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

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 {
        _from = getInternetAddress(msg.getFrom())[0];
        _to = getInternetAddress(msg.getRecipients(Message.RecipientType.TO));
        _cc = getInternetAddress(msg.getRecipients(Message.RecipientType.CC));
        _subject = msg.getSubject();
        _content = contenu;
        _sendDate = msg.getSentDate();
        _receivedDate = msg.getReceivedDate();
        
    }
[/code]

Ensuite il suffit d'utiliser la fonction getContent ...

Voila ce n'est peut-être pas la solution parfaite mais elle sera sans doute utile à certains.

Commentaire de twelding le 02/03/2007 13:05:49

Ca a l'ir très bien MAIS... et oui il y a un "mais"... j'obtiens une erreur qui est la suivante:

Exception in thread "main" javax.mail.NoSuchProviderException: No provider for pop
at javax.mail.Session.getProvider(Session.java:249)
at javax.mail.Session.getStore(Session.java:323)
at acquisition.MailReceiver.<init>(MailReceiver.java:67)
at acquisition.MailReceiver.<init>(MailReceiver.java:79)
at acquisition.MailReceiver.main(MailReceiver.java:114)

Là où ça coince, c'est :

final URLName urln = new URLName("pop3", host, port, null, userName,password);
_store = session.getStore(urln);

Dans le constructeur principal. Et bien entendu je me demande pourquoi.

Une idée? Merci

Commentaire de twelding le 02/03/2007 13:26:51

Ok, désolé, il suffisait que j'ajoute le pop3.jar qui me manquait.

Commentaire de simo5266 le 02/04/2007 18:45:08

Bonjour,

J'ai un petit probleme le voila ;
Exception in thread "main" java.lang.SecurityException: Access to default session denied
at javax.mail.Session.getDefaultInstance(Session.java:292)
at MailReceiver.<init>(MailReceiver.java:63)
at test.main(test.java:32)
est ce que ya qq'1 ki peut m'expliquer d'ou vient ce prob?

merci d'avance

Commentaire de christools7 le 13/04/2007 13:00:44

bonjour ,moi mon probleme c'est de pouvoir lire/telecharger les pièces jointe avec javaMail :-(
si vous avez des astuces et exemples de cote je suis preneur
Merci

Commentaire de sbouubi le 18/04/2007 15:16:41

Salut à tous. Mon souci à moi c'est que j'arrive bien à me connecter à mon compte gmail et lire mes messages mais qu'une seul fois.
Est ce que quelqu'aurais une idée ?

Commentaire de mourad3035 le 01/05/2007 23:21:55

Salut a tous,
je n'arrive pas a envoyer un simple mail avec mon compte gmail aider moi

Commentaire de Syplex le 22/06/2007 12:01:45

Salut tout le monde,

J'ai mis a essai ce code qui m'a l'air somme toute tres bien, neanmoins qd je le lance je recois un message d'insulte de ce type la :

invalid SHA1 signature file digest for javax/activation/DataContentHandlerFactory.class
java.lang.SecurityException: invalid SHA1 signature file digest for javax/activation/DataContentHandlerFactory.class

at sun.security.util.SignatureFileVerifier.verifySection(SignatureFileVerifier.java:351)
at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:203)
at java.util.jar.JarVerifier.processEntry(JarVerifier.java:258)
at java.util.jar.JarVerifier.update(JarVerifier.java:213)
at java.util.jar.JarFile.initializeVerifier(JarFile.java:363)
at java.util.jar.JarFile.getInputStream(JarFile.java:437)
at sun.misc.URLClassPath$5.getInputStream(URLClassPath.java:683)
at sun.misc.Resource.getBytes(Resource.java:75)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:472)
at java.net.URLClassLoader.access$500(URLClassLoader.java:109)
at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:848)
at java.security.AccessController.doPrivileged1(Native Method)
at java.security.AccessController.doPrivileged(AccessController.java:389

at java.net.URLClassLoader.findClass(URLClassLoader.java:371)
at java.lang.ClassLoader.loadClass(ClassLoader.java:570)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:442)
at java.lang.ClassLoader.loadClass(ClassLoader.java:502)


Si ca parle a qq un je suis preneur de conseils...

Merci d'avance !

Commentaire de dieyeline le 22/06/2007 14:10:23

Salut tout le monde,

J'essai ce code qd je le lance je recois un message de ce type :
Exception in thread "main" java.lang.SecurityException: class "javax.mail.internet.MimePart"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(ClassLoader.java:775)
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:487)
at java.lang.ClassLoader.defineClass(ClassLoader.java:614)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)

si qlq a une idée s8 preneur

Commentaire de Syplex le 22/06/2007 15:02:16

j'ai trouvé la solution !
En gros j'avais une archive jar qui etait bonne sous la jdk 1.3 mais pas bonne sous la 1.4... Une fois supprimée tout fonctionne !
Merci pour le code !

Commentaire de dieyeline le 22/06/2007 19:32:14

Merci Syplex par la meme occasion gé pu resoure mon blem j'avais d'autre package qui avaient les memes classes il fallait les suprimez

Commentaire de karoudja le 16/10/2007 12:13:10

En essayant d'envoyer un email via mon serveur SMPT (ssl) j'ai eu cette erreur:

Exception in thread "main" javax.mail.MessagingException: Exception reading response;
  nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1407)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1205)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)

visiblement il y a un problème avec la création des clefs. QQun a déjà eu ce genre de problème??? je ne vois vraiment pas comment résoudre cette erreur... merci

Commentaire de hero01 le 03/07/2008 15:57:34

bonjour, mon problem c ke j'execute pour recevoire mes nc mail sur gmail rien ne se passe.

Commentaire de ninas le 02/12/2008 00:12:30

a la reception j'utilise gmail ou hotmail et ça me renvois:

Exception in thread "main" javax.mail.MessagingException: Connect failed;
  nested exception is:
java.net.UnknownHostException: pop3hot.com
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:161)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at mail.MailReceiver.getMessages(MailReceiver.java:87)
at mail.MailReceiver.main(MailReceiver.java:116)
Caused by: java.net.UnknownHostException: pop3hot.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:94)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:214)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:157)
... 5 more


quelqu'un a t il une idée?
merci

Commentaire de Syplex le 02/12/2008 19:24:55

a mon avis ton paramètre pop est pas bon. Tu es sur que pop3hot.com est correct?
Essai un pop du type pop.orange.fr (pour orange) ou autre que tu connaitrais.

Commentaire de Cain le 23/07/2009 12:46:01

Bonjour,

ton code est bien utile mais toutefois il ya une erreur: dans la méthode setContent(final Message message, final MimeMultipart alternative, final MimeMultipart attachment, final String body)

// Contenu mixte: Pièces jointes + texte
if (0 != alternative.getCount() || null != body)

LE REMPLACER PAR
if (0 != alternative.getCount() && null != body)

Salutations!!!

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

envoie de mails via des threads.... besoin de plusieurs instances d'envoyeurs de mails [ par yvann75 ] bonjour,j'ai fais un client mail qui me permet d'envoyer des mails via les serveurs pop de ces comptes (gmail, yahoo., ....)lorsque j'envoie des mails envoie de piece jointe javamail [ par nagui79 ] Comment je peux envoyer une piece jointe par l'api javamail a travers un reseau local sans utiliser le reseau internet? merci d'avance pour votre aide questio sur javamail [ par khamine ] Je travaille sur une application ou j'envoie des mail grace &#224; l'api javamail;&nbsp;je me deande s'il est possible de s'assurer&nbsp;qque l'envoie JEditorPane et Applets [ par louatiamin ] le code est mis en ba il permet de charger des pages html dans un panel JEditorPanebon le probleme est que lorsque la page a charger elle meme contien Lecture des fichiers videos mxf ? [ par madjic_ouf ] Salut a tous, je suis un noob en java mais je dois reussir pour mon projet a lire des fichiers au format "mxf" (le dernier format video de ouf pour pr Fermer une page HTML [ par p0236 ] Salut a tous !!!G un soucis, grace &#224; une application Java je lance un explorateur.Ce que je voudrai c'est, apres un certain temps, refermer cette [Java] lecture particulière d'un fichier ... [ par bogdaboco ] Bonjour, J'ai un serieux soucis qui me retarde dans la r&#233;aliation de mon projet: Au d&#233;part, je lis simplement un fichier &#224; partir duque programme JAVA qui permet de generer du code HTML [ par onini ] Voila j'ai programme a realiser en Java qui permet de generer du code html, ou bien une page html souhaiter par l'utilisateur. Mon souci est que je n generer du code Html avec Java [ par onini ] J'aimerai pouvoir faire un programme en JAVA qui genere dans une fenetre Xterm du code HTML. C'est a dire que lorsque je lancerai le programme (en aya filtrer et extraire code HTML [ par luck_y6 ] Bonjour &#224; tous, Je d&#233;bute en JAVA et j'essais de filtrer le code HTML d'une page pour pouvoir traiter son contenu. pour ce fitrage j'ai ut


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mars 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728
293031    

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,702 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales