how to send attachment using sendmail - java

I am use this class to send mail it works but now i wants to add attachment how to add it please help if u can
public static void sendMail(String subject, String body, String toEmail, String ccEmail, String fromMail)
throws IOException {
Random generator = new Random();
int r = Math.abs(generator.nextInt());
body = body.replaceAll("(\\r|\\n)", "");
body = body.replaceAll("\"", "\\\\\"");
body = body.replaceAll("&", "\\\\&");
body = body.replaceAll("©", "\\\\©");
//body = body.replaceAll("> <", ">\\\n<");
if(CommonUtils.emptyString(fromMail))
fromMail = "No Reply <iotasol#pcc.com>";
else
fromMail = "No Reply <"+fromMail+">";
ProcessBuilder processBuilder = new ProcessBuilder(
ApplicationProperties.MAIL_SENDER_SH_PATH, CommonUtils.getEmptyStringForNull(subject), CommonUtils.getEmptyStringForNull(body),
toEmail, ccEmail, String.valueOf(r), fromMail);
processBuilder.start();
}

as an idea if you need to send images: make it inline with base64.
Attachments depends on library used, mail server used and so on.

MimeBodyPart messageBodyPart = new MimeBodyPart();
File file = new File("somefile.txt");
if (file.exists()) {
DataSource source = new FileDataSource("somefile.txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}

From your code example, I can tell that you are using external mail program for sending emails. You create a ProcessBuilder and invoke an OS tool for sending emails.
I would not use this solution. First, it depends on the OS (on windows you don't have the mail command). Second, this is not efficient; since you create external process for this (imagine sending many emails).
Instead, try using existing mail solution in java (you will need: mail.jar and activation.jar). With it you can send emails directly from your application, not depending on external tool.
While with mail Java library you can do everything you want, you may also look at Jodd Email. This is a small, but convenient wrapper over java mail library, that can help you with sending emails and attachments. As you can see in section 'Email using fluent API', you can do the following:
Email email = Email.create()
.from("from#foo.org")
.to("to#bar.com")
.subject("test")
.addText("Hello!")
.addHtml(
"<html><body><h1>Hey!</h1>" +
"<img src='cid:c.png'><h2>Hay!</h2></body></html>")
.embed(attachment().bytes(new File("d:\\c.png")))
.attach(attachment().file("d:\\b.jpg"));
In this example you can see two ways how you can attach your files: embedding them so they appear in HTML content, or common attaching. Of course, you don't have to use fluent interface, its just one option with this library.

Related

Apache Commons Email, how to email attachment with Content-Transfer-Type as quoted-printable?

I have an app that talks to someone else's server by sending emails with attachments.
I used Apache Commons Email to send the email with attachment like so:
MultiPartEmail email = new MultiPartEmail();
email.setHostName(sHostName);
email.addTo("bob#bob.com");
email.addFrom("andy#andy.com");
email.setSubject("the subject");
email.setMsg("the message");
byte[] documentFile = /* ... */;
String filename = "my file.pdf";
String description = "this is my file";
email.attach(new ByteArrayDataSource(myPDF, "application/pdf"), filename, description, EmailAttachment.ATTACHMENT);
email.send();
The problem is, the guy at the other end says "the header info has a Content-Transfer-Encoding value of "7bit" and it needs to be "quoted-printable".
My question is, how do I make this change so the file is attached in the appropriate way?
Rob
Commons email decides based on the content of the attachment which encoding to use, see http://thecarlhall.wordpress.com/2010/09/01/setting-quoted-printable-in-a-commons-email-body-part/ for some related discussion. Also the underlying java-mail seems to do this automatically according to the javadoc.
The blog-post states that you can try to use
email.addHeader("Content-transfer-encoding", "quoted-printable");
but it may corrupt other parts of the mail as a result.

This message uses a character set that is not supported by the InternetService?

I am using Spring JavaMailSender for sending mail from our web-application. Until now it works great, except for this case: one of our customers reported that their email client can't read the characters in email, and show:
This message uses a character set that is not supported by the
Internet Service. To view the original message content, open the
attached message. If the text doesn't display correctly, save the
attachment to disk, and then open it using a viewer that can display
the original character set.
The strange thing is that only one person see this error. Others see the emails just fine. The troubled user is using Hotmail.
I searched through several forums, most of them are about frustrated customers about their email clients, but there's not many solutions/work arounds for server side. Some say that it's because of an in-the-way SMTP server doesn't support Unicode, but I don't think it's the case...
Here's my (simplified) code:
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(new InternetAddress("abc#abc.abc","Hoang Long"));
helper.setReplyTo("abc#abc.abc");
helper.setTo(student.getEmail());
helper.setSubject(emailSubject);
helper.setCc(studioParameterService.getAllCCEmailAddress(studio.getId()));
helper.setSentDate(new Date());
helper.setText(emailContent, true);
for (String filePath : attachFileList) {
FileSystemResource attachFile = new FileSystemResource(filePath);
helper.addAttachment(attachFile.getFilename(), attachFile);
}
mailSender.send(helper.getMimeMessage());

Email attachments not included within Glassfish

I have a MailMessage class I've written to manage sending email from my application. It works fine for plain text messages, and the attachment logic works when I compile and run it manually on the command line, but it fails to include my attachments when I'm running it within Glassfish 3.1. I'm assuming there must be some subtle class loading problem that I'm clobbering on the command line by having my CLASSPATH environment set, but I haven't been able to figure out what application server setting I need to change. Here's the code I use to create and send my mail message when running on the command line:
public static void main(String[] args) throws Exception {
String[] toAddr = new String[] {"steve.ferguson#epsilon.com"};
String subject = "This is a test";
String data = "This is a message body";
MailMessage mailMessage = new MailMessage(toAddr, subject, data);
mailMessage.addAttachment(new File("/etc/hosts"), "text/plain");
mailMessage.send();
}
If I change this function to a method called by my servlet, with debugging enabled, the resulting mail message looks like this:
[#|2011-11-17T11:21:37.710-0500|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=105;_ThreadName=Thread-1;|Date: Thu, 17 Nov 2011 11:21:37 -0500 (EST)
From: sender#mydomain.com
To: steve.ferguson#mydomain.com
Message-ID: <9116840.7.1321546897580.JavaMail...>
Subject: This is a test
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_6_16232037.1321546897569"
.
|#]
By comparison, when I run the same code on the command line, it shows all of the attachments, each with the separate message boundary. This is the function I'm using to add the attachments to the underlying MimeMessage:
private Multipart buildMultipartMessage(String messageBody)
throws MessagingException {
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(messageBody.toString());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
// Attach each of our files
for (File part : attachment.keySet()) {
BodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(new FileDataSource(part)));
attachmentPart.setFileName(part.getName() + ".txt");
attachmentPart.setHeader("Content-Type", attachment.get(part));
attachmentPart.setHeader("Content-ID", part.getName());
attachmentPart.setDisposition(Part.ATTACHMENT);
multipart.addBodyPart(attachmentPart);
}
return multipart;
}
Which is called and used like this by my MailMessage class:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#mydomain.com"));
InternetAddress[] addresses = new InternetAddress[mailTo.length];
for (int i = 0; i < mailTo.length; i++)
addresses[i] = new InternetAddress(mailTo[i]);
message.setRecipients(Message.RecipientType.TO, addresses);
message.setSubject(subject);
message.setSentDate(new Date());
Multipart multipart = buildMultipartMessage(messageBody.toString());
message.setContent(multipart);
Again, all of this code, exactly as is, compiles, runs, and produces a valid email with attachments when run on the command line. It's only when I do the same thing within Glassfish that I get an empty message.
Any suggestions on how to diagnose this would be most appreciated.
Steve
UPDATE:
If I add this code after the call to buildMultipartMessage(), but before message.setContent(multipart), I can see that the content is correct:
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/var/tmp/stf"));
multipart.writeTo(bos);
bos.close();
} catch (Exception ex) { }
The /var/tmp/stf file contains the full message body with attachments and separators. I'm still confused as to why this works from the command line, but not within Glassfish, but the information may be useful in resolving the problem.
It turned out that my solution to this problem caused the current problem. Having javax.mail.jar in my boot classpath and activation.jar in my endorsed directory was the only way I could get email handling working with the logger, but then they didn't work for normal usage. I have no idea why this is, but I found that eliminating the -Xbootclasspath option and removing activation.jar from my endorsed directory fixed the problem. If anyone has any speculation as to why, I'd be glad to do some more testing and report back. For now, I guess I have to live without email logging, because the attachments are a requirement for my application.
Perhaps if I switch to log4j instead of using the native Java EE 6 logging, I can have the best of both worlds.

why mail content is sent as attachment when I send it to Hotmail account?

why mail content is sent as attachment when I send it to Hotmail account?
When I send mail to a Hotmail account the body of the mail is sent as attachment. But when sent to other accounts like yahoomail, gmail it is not creating any problem.
I want to know why I am getting problem with Hotmail accounts.
Please give me a solution for this.
MimeMessage msg = createMimeMessage(sender, emsg,session,mail.companyName); Transport.send(msg);
Multipart multipart = new MimeMultipart();
// This is the template Attachment part
if (emsg.getAttachment() != null) {
for (File file : emsg.getAttachment()) {
MimeBodyPart messageAttachmentBodyPart = new MimeBodyPart();
messageAttachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentBodyPart.setDataHandler(new DataHandler(source));
messageAttachmentBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageAttachmentBodyPart);
}
}
Right. So, what happens if you send a file from a gmail account to a hotmail account, does it get attached? Or is it displayed just as you want? My guess is that attaching the file is a security measure to prevent malicious code from being activated on display. This mechanism might also be selective, meaning that it depends on the sender (an interesting post to read on this matter is this one).
Another thought: why is that a problem anyway?
Might help if you add
messageAttachmentBodyPart.setDisposition(Part.INLINE);

How do I send a binary attachment in an email with Java using the JavaMail API?

Using JDK1.5 how does one send a binary attachemnt (such as a PDF file) easily using the JavaMail API?
Have you looked at the JavaMail FAQ? It seems to have little snippets to demonstrate the process (and how to fix a common problem -- running out of memory).
Assuming that you don't want to read some links and don't want any external dependencies, you need to use MimeMultipart and BodyPart:
MimeMultipart messageContent = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(yourFile);
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName("MyFile.ext");
bodyPart.setDisposition(Part.ATTACHMENT);
// Then add to your message:
messageContent.addBodyPart(bodyPart);
Attaching a body to the messages is just attaching a BodyPart with disposition Part.INLINE
If you want to do it easily I'd suggest using Commons-Email! It's built on the JavaMail API, but it makes it much simpler.
There is a sample in the User Guide on how to send email with attachments... it's much easier than using the standard JavaMail API!

Categories