1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail {
public static void envoiMail(String from, String to, String cc, String sujet, String texte, PieceJointe pj, String signature) {
// Création de l'objet Properties qui contient tous les paramètres d'initialisation nécessaires.
Properties props = new Properties();
props.put("mail.smtp.host", "chrmt-smtp01");
Session session = Session.getInstance(props, null);
try {
// Création de l'objet message
MimeMessage msg = new MimeMessage(session);
msg.setSubject(sujet); // Ajout du sujet
msg.setFrom(from); // Ajout du from ==> Erreur
msg.setRecipients(Message.RecipientType.TO, to); // Ajout du destinataire
msg.setRecipients(Message.RecipientType.CC, cc); // Ajout du destinataire en copie
// Ajout du contenu au message
msg.setContent(createMultipart(texte, pj, signature));
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
public static MimeMultipart createMultipart(String texte, PieceJointe pj, String signature) throws MessagingException {
MimeMultipart mp = new MimeMultipart();
// 1ere partie du message : Le texte
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(texte, "ISO-8859-1", "html");
mp.addBodyPart(mbp1);
// 2ème partie du message : La pièce jointe
if(pj != null) {
MimeBodyPart mbp2 = new MimeBodyPart();
DataSource source = new FileDataSource(pj.getFile());
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName(pj.getName());
mp.addBodyPart(mbp2);
}
// 3ème partie du message : La signature
MimeBodyPart mbp3 = new MimeBodyPart();
mbp3.setText(signature, "ISO-8859-1", "html");
mp.addBodyPart(mbp3);
return mp;
}
} |
Partager