I have java code for sending email with attachment as below.
String myEmailId = "xx#yahoo.co.in";
String myPassword = "#xx";
String senderId = "yy#gmail.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.mail.yahoo.com");
email.addTo(senderId);
email.setFrom(myEmailId);
email.setSubject("The picture");
email.setMsg("<font face='verdana' size='3'>Here is the picture you wanted "
+ "<table>"
+ "<tr><th>id</th><th>Name</th></tr>"
+ "<tr><th>1</th><th>Name 1</th></tr>"
+ "<tr><th>2</th><th>Name 2</th></tr>"
+ "<tr><th>3</th><th>Name 3</th></tr>"
+ "<tr><th>4</th><th>Name 4</th></tr>"
+ "</table>"
+ "</font>");
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test_small.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
// send the email
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
All is working fine EXCEPT, the HTML code is displaying as it is.
In Email what I get is
<font face='verdana' size='3'>Here is the picture you wanted <table><tr><th>id</th><th>Name</th></tr><tr><th>1</th><th>Name 1</th></tr><tr><th>2</th><th>Name 2</th></tr><tr><th>3</th><th>Name 3</th></tr><tr><th>4</th><th>Name 4</th></tr></table></font>
Is there any parameter, email that I will receive will have proper HTML formatted data.
Note :
Actually I was using Email email = new SimpleEmail(); and doing above stuff where HTML part is working perfectly. However when I had to switch to attachment, I had to use MultiPartEmail email = new MultiPartEmail();.
I want to provide my answer here such that future me (and others) can see the complete code. For whatever reason, probably just me, I found these answers incomplete, or that they did not work for me. Like OP, I was trying to send an HTML based email with a PDF attachment. Here is what I ended up with using commons-email 1.4. Any comments will be appreciated.
Imports:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.EmailAttachment;
Build your email object (obviously the actual details here should be yours)
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.yourhosthere.com");
email.setSmtpPort(25);
// authentication not always needed depending on your environment
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setTo("to#yourhosthere.com");
email.setFrom("from#yourhosthere.com");
Now your message details. Note that my HTML includes the HTML and BODY tags.
email.setSubject("Your subject here");
email.addPart("<div>Your html here</div>", "text/html; charset=UTF-8");
Now the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(filepath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
Now send the email
email.send();
I got answer.
Just changed MultiPartEmail email = new MultiPartEmail(); to MultiPartEmail email = new HtmlEmail();
You can't use email.setMsg()
But set message body as:
email.addPart( "<h1>MSG BODY</h1> <u>your</u> name", "text/html; charset=UTF-8" );
Related
I'm trying to send email with inline attachment using MS Graph. I know how to send email without attachment but when I'm trying to send message with attachment I don't know how can I add this attachment to the message.
Here is my code:
// recipients
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "tom#mail.com";
recipient.emailAddress = emailAddress;
List<Recipient> recipients = List.of(recipient);
// body
ItemBody body = new ItemBody();
body.contentType = BodyType.HTML;
body.content = "<html><body>my image:<br><img src='cid:my_image_CID'></body></html>";
// inline image
Attachment attachment = new Attachment();
attachment.isInline = true;
attachment.contentType = ".png";
attachment.id = "my_image_CID";
//attachment.contentBytes - I DON'T SEE THIS FIELD...
// message
Message message = new Message();
message.subject = "my subject";
message.body = body;
message.toRecipients = recipients;
//message.attachments = ??? - how to create this object?
there are examples in the internet that I can set attachment.contentBytes but I don't see this attribute.
For the message I can set attachments object which is of type
AttachmentCollectionPage
but I don't know how can I create this object.
I'm using the following versions:
Microsoft Graph Java SDK » 5.42.0
Microsoft Graph Java Core SDK » 2.0.14
You need to use FileAttachment which extends Attachment and has property contentBytes.
I want to write a service through which I can create a email message with (to, cc, bcc, subject, body) specified. Then I need to return this email message to front end and download it in ".oft" format, in such a way that when I click on this downloaded file; file should open with all the fields (to, cc, bcc, subject, body) populated.
I am using Java as backend technology and angular5 as front-end.
I have tried using javax.mail utility to create the email message and return it as byte array. Something like:
Properties prop = System.getProperties();
Session session = Session.getDefaultInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("emailAddr#domain.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("emailAddr#domain.com"));
msg.setSentDate(new Date());
msg.setSubject("subject");
msg.setText("text of msg");
//return it from service API as
response.getOutputStream().write(msg.toString().getBytes());
On front end (component.ts file) I am retrieving the response as :
//function gets called on button click
createEmailTemplate():void{
this.httpService.getEmail('serviceUrl')
.subscribe(
email => {
let filename = "SampleMailFile.oft";
let linkElement = document.createElement('a');
let blob = new Blob([email], { type: "message/rfc822"});
let url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
let clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
);
}
A MSG file is supposed to have the same format as an OFT file. If that’s true then you should be able to use jotlmsg to generate the file. You shouldn’t need to use JavaMail at all for this, since it’s intended to actually send the mail.
NOTE: I’ve not used this library before, so I can’t speak to whether this will truly work.
I created an email sending job which pics the receivers email id from the excel sheet and an email content from the html file(with embedded image) both placed in a system locally.
But when the mail is sent through the job the image is not visible in MS Outlook but visible in yahoo and gmail as an attachment.
email sending code:
while (it.hasNext())
{
ReadHTMLContent content = new ReadHTMLContent();
MimeMultipart multipart = new MimeMultipart("related");
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
to = (String) it.next();
b = to.matches(emailCheck);
if (b!= null && b == true) {
MimeMessage message = new MimeMessage(session);
msgContent = fetchMailContent();
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("This is the Subject Line!");
messageBodyPart1.setContent(msgContent, "text/html");
multipart.addBodyPart(messageBodyPart1);
String collect = content.getImageSrc();
String imgStrng = collect;
DataSource fds = new FileDataSource(imgStrng);
messageBodyPart2.setDataHandler(new DataHandler(fds));
messageBodyPart2.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent message successfully to " + to);
} else {
System.out.println("Invalid Email ID " + to);
}
}
Sample HTML from where i am getting the mail content has an embedded image, stored locally in a system:
<html>
<head><title>Sample test mail job</title></head>
<body bgcolor=white>
<table border="0" cellpadding="10">
<tr>
<td>
<h1>Testing EMail crone job</h1>
</td>
</tr>
</table>
<p>Weather is cold today </p>
<tr>
<td>
<img src="D:\\Email POC\\images\\Koala.jpg">
</td>
</tr>
</body>
</html>
Please let me know how is it possible to make it visible in outlook mail box as well.
Thanks in advance.
Outlook uses Word as an email editor. You can read about supported and unsupported HTML elements, attributes, and cascading style sheets properties in the following articles in MSDN:
Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007 (Part 1 of 2)
Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007 (Part 2 of 2)
img src=" "
You need to add a reference to an image loaded to any web server or add an image as a hidden attachment. So, the result markup should look like the following one:
img src="cid:attachmentName"
Add the attachment using the Attachments.Add method.
Set the PR_ATTACH_CONTENT_ID property using the PropertyAccessor object.
Set the cid value (see #2) for the reference in the message body.
string img = "<br/><p><o:p><img src=\"" + att.FileName
+ "\" width=1 height=1 border=0 /></o:p></p>";
item.HTMLBody = item.HTMLBody.Replace("</body>", img + "</body>");
string PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E";
string HIDDEN_ATTACHMENT = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B";
var pa = att.PropertyAccessor;
if (pa != null)
{
pa.SetProperty(PR_ATTACH_CONTENT_ID, att.FileName);
pa.SetProperty(HIDDEN_ATTACHMENT, false);
}
The msgContent string needs to reference the attached image using the Content-Id you've specified, i.e., using:
<img src="cid:image"/>
If msgContent is being created by some other program, you may need to process the html and change the references to the image.
I am using JavaMail library, I would like to change the body of the emails, sentences in different color? How can I do it? My application is in (Swing/JFrame)
An example of sending email as HTML: http://www.tutorialspoint.com/java/java_sending_email.htm
What Baadshah is suggesting is adding all of your color formatting inside the Content string using html tags.
message.setContent("<h1>This is actual message</h1>",
"text/html" );
You can programatically construct the string that contains the body message.
String line1 = "This is the first line in the body. We want it to be blue."
addColor(line1, Color.BLUE);
Then create a method for handling the colorizing html:
public static String addColor(String msg, Color color) {
String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
String colorMsg = "<FONT COLOR=\"#" + hexColor + "\">" + msg + "</FONT>";
return colorMsg;
}
You can examine different ways of colorizing in HTML here: http://www.htmlgoodies.com/tutorials/colors/article.php/3479011/How-To-Change-Text-Color-Using-HTML-and-CSS.htm. This includes old ways of doing it, like using FONT (as my example above) or modern ways of doing it using CSS.
Edit: The toHexString returns an 8 Character hex code (alpha + red + blue + green) while HTML only wants the RGB without alpha. I used the solution from this link, and setup a SSCCE:
import java.awt.Color;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailTestHTML
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "targetemail#somehost.com";
// Sender's email ID needs to be mentioned
String from = "youremail#somehost.com";
// Assuming you are sending email from localhost
String host = "putYourSMTPHostHere";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// String with body Text
String bodyText = addColor("This line is red.", Color.RED);
bodyText += "<br>" + addColor("This line is blue.", Color.BLUE);
bodyText += "<br>" + addColor("This line is black.", Color.BLACK);
System.out.println(bodyText);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent(bodyText,
"text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static String addColor(String msg, Color color) {
String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
String colorMsg = "<FONT COLOR=\"#" + hexColor + "\">" + msg + "</FONT>";
return colorMsg;
}
}
Note:
In my environment I had to set this argument in the Run Configuration:
-Djava.net.preferIPv4Stack=true
More on that here.
Its just css.
Nothing to do with JAVA.The browser detects your HTML content which you are sending in email.
For example
<div style="font-size:14px">Dear user</div>
You have to send the mail in HTML format to be able to change text color.
See the JavaMail FAQ.
For me this worked flawlessly, Worth a shot :
String htmlText2 = "<font color=red>Jon Targaryen</font>\n";
or if you want to use hex color :
String htmlText2 = "<font color=#93cff2>Jon Targaryen</font>\n";
You can add more attributes like Headings or Bold :
String htmlText2 = "<H1><font color=red>Jon Targaryen</font></H1>\n";
String htmlText2 = "<b><H1><font color=red>Jon Targaryen</font></H1></b>\n";
I am using Amazon Simple Email Service java API to send mail to receivers.
I am sending URL in mail body inside tag.
My use case demands the user to double click on the URL received to prompt some action. (like confirmation mail)
Problem is the url gets encoded while receiving. On double clicking it gives page not found (404) error.
Original URL : http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true
When i double click on this URL on mail, the link is opened in address bar as :
http://something.com/confirm/email=abc%40hotmail.com%26regKey=somekey%26confirm=true
I am using AmazonSimpleEmailServiceClient. Code is below :
SendEmailRequest request = new SendEmailRequest().withSource(sourceAddress);
String confirmationURL="http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true";
List<String> toAddresses = new ArrayList<String>();
toAddresses.add(toEmail);
Destination dest = new Destination().withToAddresses(toAddresses);
request.setDestination(dest);
Content subjContent = new Content().withData("Confirmation Request");
Message msg = new Message().withSubject(subjContent);
// Include a body in both text and HTML formats
Content textContent = new Content().withData("Dear please go to the following URL:"+
confirmationURL+"\n\n");
Content htmlContent = new Content().withData("<p>Dear please go to the following URL:</p>"+
"<p>"+confirmationURL+"</p>");
Body body = new Body().withHtml(htmlContent).withText(textContent);
msg.setBody(body);
request.setMessage(msg)
UPDATE
Just found, this problem is occurring only when recipient email is in hotmail.com. Why microsoft always have to do something differently ? Somebody help !
Use the class java.net.URLEncoder:
String confirmationURL = URLEncoder.encode( "http://something.com/confirm/email=abc#hotmail.com®Key=somekey& confirm=true", "UTF-8");