use of javax.activation.FileDataSource in project perun by CESNET.
the class MessagePreparator method createAttachment.
/**
* Creates attachment from filename
*
* @param filename
* @return
* @throws Exception
*/
private BodyPart createAttachment(String filename) throws Exception {
BodyPart attachBodypart = new MimeBodyPart();
File file = new File(filename);
FileDataSource fds = new FileDataSource(file);
DataHandler dh = new DataHandler(fds);
attachBodypart.setFileName(file.getName());
attachBodypart.setDisposition(Part.ATTACHMENT);
attachBodypart.setDescription("Attached file: " + file.getName());
attachBodypart.setDataHandler(dh);
logger.debug("ATTACHMENT ADDED ; filename: " + filename);
return attachBodypart;
}
use of javax.activation.FileDataSource in project jmeter by apache.
the class SendMailCommand method prepareMessage.
/**
* Prepares message prior to be sent via execute()-method, i.e. sets
* properties such as protocol, authentication, etc.
*
* @return Message-object to be sent to execute()-method
* @throws MessagingException
* when problems constructing or sending the mail occur
* @throws IOException
* when the mail content can not be read or truststore problems
* are detected
*/
public Message prepareMessage() throws MessagingException, IOException {
Properties props = new Properties();
String protocol = getProtocol();
// set properties using JAF
props.setProperty("mail." + protocol + ".host", smtpServer);
props.setProperty("mail." + protocol + ".port", getPort());
props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));
// set timeout
props.setProperty("mail." + protocol + ".timeout", getTimeout());
props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());
if (useStartTLS || useSSL) {
try {
String allProtocols = StringUtils.join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
logger.info("Use ssl/tls protocols for mail: " + allProtocols);
props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
} catch (Exception e) {
logger.error("Problem setting ssl/tls protocols for mail", e);
}
}
if (enableDebug) {
props.setProperty("mail.debug", "true");
}
if (useStartTLS) {
props.setProperty("mail.smtp.starttls.enable", "true");
if (enforceStartTLS) {
// Requires JavaMail 1.4.2+
props.setProperty("mail.smtp.starttls.require", "true");
}
}
if (trustAllCerts) {
if (useSSL) {
props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
} else if (useStartTLS) {
props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
}
} else if (useLocalTrustStore) {
File truststore = new File(trustStoreToUse);
logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
}
}
if (useSSL) {
// Requires JavaMail 1.4.2+
props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
props.put("mail.smtps.ssl.socketFactory.fallback", "false");
} else if (useStartTLS) {
// Requires JavaMail 1.4.2+
props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
props.put("mail.smtp.ssl.socketFactory.fallback", "false");
}
}
session = Session.getInstance(props, null);
Message message;
if (sendEmlMessage) {
message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
} else {
message = new MimeMessage(session);
// handle body and attachments
Multipart multipart = new MimeMultipart();
final int attachmentCount = attachments.size();
if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
if (attachmentCount == 1) {
// i.e. mailBody is empty
File first = attachments.get(0);
try (FileInputStream fis = new FileInputStream(first);
InputStream is = new BufferedInputStream(fis)) {
message.setText(IOUtils.toString(is, Charset.defaultCharset()));
}
} else {
message.setText(mailBody);
}
} else {
BodyPart body = new MimeBodyPart();
body.setText(mailBody);
multipart.addBodyPart(body);
for (File f : attachments) {
BodyPart attach = new MimeBodyPart();
attach.setFileName(f.getName());
attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
multipart.addBodyPart(attach);
}
message.setContent(multipart);
}
}
// set from field and subject
if (null != sender) {
message.setFrom(new InternetAddress(sender));
}
if (null != replyTo) {
InternetAddress[] to = new InternetAddress[replyTo.size()];
message.setReplyTo(replyTo.toArray(to));
}
if (null != subject) {
message.setSubject(subject);
}
if (receiverTo != null) {
InternetAddress[] to = new InternetAddress[receiverTo.size()];
receiverTo.toArray(to);
message.setRecipients(Message.RecipientType.TO, to);
}
if (receiverCC != null) {
InternetAddress[] cc = new InternetAddress[receiverCC.size()];
receiverCC.toArray(cc);
message.setRecipients(Message.RecipientType.CC, cc);
}
if (receiverBCC != null) {
InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
receiverBCC.toArray(bcc);
message.setRecipients(Message.RecipientType.BCC, bcc);
}
for (int i = 0; i < headerFields.size(); i++) {
Argument argument = (Argument) headerFields.get(i).getObjectValue();
message.setHeader(argument.getName(), argument.getValue());
}
message.saveChanges();
return message;
}
use of javax.activation.FileDataSource in project SpringStepByStep by JavaProgrammerLB.
the class SendHTMLEmailWithTemplate method main.
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(new File("settings.properties")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Testing Subject");
BodyPart body = new MimeBodyPart();
// freemarker stuff.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("html-mail-template.ftl");
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put("to", "liubei");
rootMap.put("body", "Sample html email using freemarker");
rootMap.put("from", "liubei");
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker stuff ends.
/* you can add html tags in your text to decorate it. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = "hello.txt";
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html;charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Done....");
}
use of javax.activation.FileDataSource in project SpringStepByStep by JavaProgrammerLB.
the class SendAttachmentInEmail method main.
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "destinationemail@gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail@gmail.com";
//change accordingly
final String username = "manishaspatil";
//change accordingly
final String password = "******";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
use of javax.activation.FileDataSource in project gitblit by gitblit.
the class MailService method createMessage.
/**
* Create a message.
*
* @param mailing
* @return a message
*/
public Message createMessage(Mailing mailing) {
if (mailing.subject == null) {
mailing.subject = "";
}
if (mailing.content == null) {
mailing.content = "";
}
Message message = new MailMessageImpl(session, mailing.id);
try {
String fromAddress = settings.getString(Keys.mail.fromAddress, null);
if (StringUtils.isEmpty(fromAddress)) {
fromAddress = "gitblit@gitblit.com";
}
InternetAddress from = new InternetAddress(fromAddress, mailing.from == null ? "Gitblit" : mailing.from);
message.setFrom(from);
Pattern validEmail = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
// validate & add TO recipients
List<InternetAddress> to = new ArrayList<InternetAddress>();
for (String address : mailing.toAddresses) {
if (StringUtils.isEmpty(address)) {
continue;
}
if (validEmail.matcher(address).find()) {
try {
to.add(new InternetAddress(address));
} catch (Throwable t) {
}
}
}
// validate & add CC recipients
List<InternetAddress> cc = new ArrayList<InternetAddress>();
for (String address : mailing.ccAddresses) {
if (StringUtils.isEmpty(address)) {
continue;
}
if (validEmail.matcher(address).find()) {
try {
cc.add(new InternetAddress(address));
} catch (Throwable t) {
}
}
}
if (settings.getBoolean(Keys.web.showEmailAddresses, true)) {
// full disclosure of recipients
if (to.size() > 0) {
message.setRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));
}
if (cc.size() > 0) {
message.setRecipients(Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()]));
}
} else {
// everyone is bcc'd
List<InternetAddress> bcc = new ArrayList<InternetAddress>();
bcc.addAll(to);
bcc.addAll(cc);
message.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
}
message.setSentDate(new Date());
// UTF-8 encode
message.setSubject(MimeUtility.encodeText(mailing.subject, "utf-8", "B"));
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(mailing.content, "utf-8");
if (Mailing.Type.html == mailing.type) {
messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
} else {
messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
}
MimeMultipart multiPart = new MimeMultipart();
multiPart.addBodyPart(messagePart);
// handle attachments
if (mailing.hasAttachments()) {
for (File file : mailing.attachments) {
if (file.exists()) {
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
multiPart.addBodyPart(filePart);
}
}
}
message.setContent(multiPart);
} catch (Exception e) {
logger.error("Failed to properly create message", e);
}
return message;
}
Aggregations