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 63 64 65 66 67 68 69 70 71 72 73 74 75
|
public MimeMessage createMessage(String from, String to, String cc, String bcc,
String subject, String message, String attachment) throws AddressException, MessagingException, IOException {
Properties properties = new Properties();
try {
InputStream in = getClass().getResourceAsStream("/faxandmail.properties");
properties.load(in);
} catch (IOException e) {
System.out.println(e.toString());
}
// Get the required properties.
String strMailHost = properties.getProperty("mailSmtpServer");
String strMailPort = properties.getProperty("mailSmtpPort");
String strMailUserName = properties.getProperty("mailUserName");
String strMailPassword = properties.getProperty("mailPassword");
String strMailFrom = from;
String strMailTo = to;
String strMailCc = cc;
String strMailBcc = bcc;
String strMailSubject = subject;
String strMessage = message;
// Put the properties to the System
Properties pProps = System.getProperties ();
pProps.put ("mail.smtp.auth", "true");
pProps.put ("mail.smtp.host", strMailHost);
pProps.put ("mail.smtp.port", strMailPort);
pProps.put ("mail.smtp.user", strMailUserName);
pProps.put ("mail.smtp.password", strMailPassword);
pProps.put ("mail.debug", "true");
pProps.setProperty("mail.transport.protocol", "smtp");
// Get the session properties
Session sSession = Session.getInstance (pProps,null);
// Create the new message
MimeMessage msgMessage = new MimeMessage (sSession);
// Set the message properties
msgMessage.setFrom (new InternetAddress (strMailFrom)); // From
msgMessage.setRecipients (Message.RecipientType.TO,
InternetAddress.parse (strMailTo, false)); // To
msgMessage.setRecipients (Message.RecipientType.CC,
InternetAddress.parse (strMailCc, false)); // CC
msgMessage.setRecipients (Message.RecipientType.BCC,
InternetAddress.parse (strMailBcc, false)); // BCC
msgMessage.setSubject (strMailSubject); // Subject
msgMessage.setSentDate (new Date ()); // Date
// First part of the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Content of the message
messageBodyPart.setText(message);
// Add attachement (MultiParts)
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
String fileName = attachment.substring(attachment.lastIndexOf("/")+1) ;
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
msgMessage.setContent(multipart);
return msgMessage;
} |
Partager