Struts 2 + email + pièce jointe
Bonjour,
J'ai un souci pour envoyer un mail avec une pièce jointe. En effet, l'email est bien envoyé mais la pièce jointe n'est pas inclue. J'ai essayé avec plusieurs serveurs smtp mais sans succès.
Si je mets ce post dans le forum Struts2, c'est que dans une application toute simple cela fonctionne très bien. Dans mon application, l'envoi de l'email se fait après une inscription (création d'un .pdf et envoi de celui par mail en pièce jointe).
Voici ma classe pour l'envoi des emails :
Code:
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 javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.internet.*;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import java.util.Properties;
public class SendMail{
private static final String SMTP_HOST_NAME = "smtp.example.com";
private static final String SMTP_AUTH_USER = "info@example.com";
private static final String SMTP_AUTH_PWD = "soleil";
public void envoyerMailSMTP(String to, String from, String subject, String body) throws Exception {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
try {
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject, "iso-8859-1");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("C:/pdf/test.pdf");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
transport.connect(SMTP_HOST_NAME, SMTP_AUTH_USER, SMTP_AUTH_PWD);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}catch (MessagingException ex){
ex.getMessage();
}
}
} |
Merci pour votre aide