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
"PROGRAMMEUR", EST UN PROGRAMME QUI PERMET DE TAPER QUELQUE ..."PROGRAMMEUR", EST UN PROGRAMME QUI PERMET DE TAPER QUELQUE CHOSE DANS UN BLOC-NOTE ET DE LE CONVERTIRE EN FICHIER DE PROGRAMMATION AVEC LE CODE SOURCE."Programmeur", est un programme pour convertire du "langage humain":
affiche, variable, main (exception), ...
En:
System.out.println("");, int/lo...
par edouard333
"NARRATEUR", PROGRAMME QUI "LIT" SE QU'ON ÉCRIT..."NARRATEUR", PROGRAMME QUI "LIT" SE QU'ON ÉCRIT..."Narrateur" est programme qui "lit" se qu'on écrit, mais je ne l'ai pas encore fini mais je le met pour voir si ça à de l'intérêt... Le programme n'es...
par edouard333
RENAME-MOARRENAME-MOARProgramme permettant de renommer plusieurs fichiers d'un répertoire sélectionné.
On peut :
- Changer le nom au complet en ajoutant une partie var...
par cotepierrot
DWIKI (DESKTOPWIKI)DWIKI (DESKTOPWIKI)Un petit wiki en Java. Il s'agit d'un projet scolaire de 2008. J'apprécierais vos commentaires car un certain prof que je ne nommerai pas a été très s...
par xsimo
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
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 à l'api javamail; je me deande s'il est possible de s'assurer 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 à 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éaliation de mon projet: Au départ, je lis simplement un fichier à 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 à tous, Je dé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
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|