Accueil > > > 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
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 };
}
}
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 :
- ☺
- 13 octobre 2005 13:48:34 :
- Ajout d'un zip
Sources de la même categorie
Commentaires et avis
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
Afficher du HTML dans une JFrame [ par onh890 ]
Salut les amis, j'aimerais bien savoir comment pourrais je afficher une page HTML dans un objet JTextField contenu dans JFrame, sachant que la méthode
Html/javascript [ par sarassef ]
Bonjour, comment pourrais je faire avec html et javascript pour afficher des objets tels qu un champ de texte lors d un clique sur un item de select?
Lecture port serie [ par benaye ]
Bonjour tout le monde, je suis débutant en java (j2me) et je développe sur un boitier (TC65i). Mon problème est que j'essaye de lire sur le port ser
Applet et IE9 [ par jopop ]
Bonjour les java-istes, Je suis en cours de développement d'une JApplet et j'étais en train de tester l'intégration de celle-ci dans une page HTML. P
ANDROID , NMEA [ par miraz123 ]
bonjour, je suis en train de developper une application sous ANDROID qui permet la lecture des trames NMEA envoyer par des satelites ensuite et apres
problème d'accès à l'url [ par tounsimaroua1 ]
salut à tous, je suis entrain de réaliser une application java necessitant la parcours d'un fichier html. j'ai trouvé un probléme d'accès à l'url j'ai
regrouper des données dans JAVA et envoie vers RTMAPS [ par akramuniversite ]
Bonjour, dans mon programme en JAVA je dois regrouper des informations venant d'une base de données et les envoyer vers un autre logiciel (RTMAPS) pou
Afficher une image sur une page HTML depuis un applet.. [ par bl4ck0utb ]
Bonjour je cherche a faire une page html et afficher une image grace au java. j'ai testé ceci: http://www.javafr.com/codes/IMAGE-DANS-APPLET_15375.as
|
Derniers Blogs
[SHAREPOINT] LES SESSIONS TECHDAYS 2012.[SHAREPOINT] LES SESSIONS TECHDAYS 2012. par Patrick Guimonet
Voici donc pour ceux qui n'ont pas pu venir, ou ceux qui n'ont pas pu toutes les suivre la liste des sessions SharePoint aux TechDays 2012, que je mettrais à jour dès que les liens des vidéo seront disponibles. Ou ici : http...
Cliquez pour lire la suite de l'article par Patrick Guimonet TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3 par ROMELARD Fabrice
Speaker: Bernard Ourghanlian Cette session est comme chaque jour transmise en live par BrainSonic, et j'ai donc suivi cette troisième pleinière par ce moyen sur mon iPad . Elle est dédiée comme chaque année à la mise en perspective de l'é...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE !MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE ! par Vko
Hier durant une session dédiée aux Techdays 2012, j'ai eu le plaisir d'annoncer la sortie de la Béta 2 de Mishra Reader. C'est quoi ? Pour les utilisateurs, c'est une vraie expérience de lecture de flux RSS sur Windows. Rien à voir avec les produit...
Cliquez pour lire la suite de l'article par Vko [FRAMEWORK 4] LES TASKS ET LE THREAD UI[FRAMEWORK 4] LES TASKS ET LE THREAD UI par fathi
Je viens de passer quelques temps au TechDay's et j'ai pu voir pas mal de session intéressante. Par contre une chose m'a un peu étonné lors de certaines de ces sessions qui abordaient les améliorations du framework .NET (donc le 4.5) : en gros, bea...
Cliquez pour lire la suite de l'article par fathi WORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBEWORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBE par JeremyJeanson
Depuis déjà un an, je conseille vivement les utilisateurs de Workflow Foundation 3 à migrer vers la version 4. L'information qui va suivre ne devrait donc pas trop prendre au dépourvu les personnes qui m'ont suivi. Je profite de ce poste, pour faire le re...
Cliquez pour lire la suite de l'article par JeremyJeanson
Forum
RE : CODE GéNéRé RE : CODE GéNéRé par Julien39
Cliquez pour lire la suite par Julien39 RE : CODE GéNéRé RE : CODE GéNéRé par Julien39
Cliquez pour lire la suite par Julien39
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|