HTML email is getting displayed as plain/text with javamail in Gmail and Yahoo - spring

Trying to send HTML email with java-mail . I can see HTML format email in Outlook but Gmail and Yahoo don't show HTML format , they are showing email as plain texts without HTML formatting .
I am using company's SMTP server to send an email to users .
I tried following and msgcontent is StringBuilder in following code :
Properties prop = System.getProperties();
prop.put("mail.smtp.auth", "false");
prop.put("mail.smtp.starttls.enable","false");
prop.put("mail.smtp.host", SMTP_SERVER);
Session session = Session.getInstance(prop);
MimeMessage msg = new MimeMessage(session);
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart content = new MimeBodyPart();
content.setHeader("content-type", "text/html");
msg.setFrom(new InternetAddress(EMAIL_FROM));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_TO, false));
msg.setSubject(EMAIL_SUBJECT);
content.setContent(msgcontent.toString(), "text/html");
multipart.addBodyPart(content);
msg.setContent(multipart);
I want HTML email to be displayed in all email clients like Gmail , Yahoo, etc. Currently only Outlook can display HTML content.

You don't really need a multipart since your message has only one part.
You can simplify the content setting by replacing the two content.set* lines with:
content.setText(msgcontent.toString(), "utf-8", "html");
What version of JavaMail are you using?
If you examine the raw MIME content of the message you receive and compare it with the raw MIME content of the message you send, are they different?

Related

JMeter: how to send formatted text via SMPT sampler

Is there a way to send a formatted text with links via JMeter SMTP sampler?
Scenario:
I need to send an email, where one of the words e.g. My "Instagram" will have a link to my instagram page.
Option 1:
Create such email in Gmail, send it to myself, then download it as .eml file and send use "Send .eml" option in SMTP sampler.
However, my issue is that these links should be changed and lead to different instagram pages with each new email sent, thus I need to pass it as a variable from CSV file. This seems to be impossible to achieve with .eml file as it needs to be modified before each request. Unless there is a way?
Option 2 (preferred):
Somehow I need to format text in "Message body" of SMTP sampler. I've tried to copy/paste the same style and tags from "Original" .eml file, but it is always sent as a plain text and Gmail won't format it on client side.
Here is an example of RAW Gmail text with formatted link which I've tried to use in "Message" text box of SMTP Sampler:
Visit my account #dummyaccount<https://l.instagram.com/?u=https%3A%2F%2Ftaplink.> for more info.
Expecting to see the following in the email:
Visit my account #dummyaccount - where #dummyaccount is a hyperlink
Actual:
Visit my account #dummyaccounthttps://l.instagram.com/?u=https%3A%2F%2Ftaplink. for more info.
Any suggestion will be greatly appreciated.
I don't think you can customize the SMTP Sampler messages this way. You will need to either compose the message in an email application, save it to .eml file and send this .eml or if you want to build the message content dynamically you can use JSR223 Sampler and Groovy language for sending your message.
Example code:
Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-server-here");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
def session = javax.mail.Session.getInstance(props, new CredentialsAuthentication() as javax.mail.Authenticator)
def msg = new javax.mail.internet.MimeMessage(session)
def from = new javax.mail.internet.InternetAddress("your-email-address-here", "your first and last name");
msg.setFrom(from);
def toAddress = new javax.mail.internet.InternetAddress("your-recipient-here ");
msg.setRecipient(javax.mail.Message.RecipientType.TO, toAddress);
msg.setSubject("Test");
msg.setContent("<html>\n" +
"<body>\n" +
"\n" +
"<a href=\"http://link-to-your-instagram-profile\">\n" +
"Link to my Instagram</a>\n" +
"\n" +
"</body>\n" +
"</html>", "text/html")
javax.mail.Transport.send(msg);
class CredentialsAuthentication extends javax.mail.Authenticator {
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("your-username#most-probably-with-email.com", "your-password-here")
}
}

Get gmail attachment's downloading URL?

I am fetching Gmail Attachment through Gmail API using the get_user_message_attachment method , but the data it sends is in Base64 encoded form. I want to get the attachment's downloadable URL, which I can store and send to the frontend of my application. Is it possible to get the URL of the attachment in some way? I do not want to convert the Base64 string to a file on my server and then upload it somewhere and send that upload's link to the front-end.
#gmail_service = Google::Apis::GmailV1::GmailService.new
#authorization stuff is done and then I fetch the attachment which is received as a Google::Apis::GmailV1::MessagePartBody response
resp = #gmail_service.get_user_message_attachment("myemail#google.com", message_id, attachment_id)
# resp.data contains the base64 encoded string
I want the attachment as a downloadable URL, so that I don't have to do the manual file conversion and uploading stuff.
The message.get method returns a Message object
This object contains the body of the message base64 encoded.
If you want a downloadable url I suggest that you convert the Base64 string to a file on your server and then upload it somewhere and send that upload's link to the front-end.
There is no other option this is the data the API returns.
You may want to consider providing a proxy endpoint on your server for your frontend. Then give your frontend a link to this endpoint with a messageId, and make your server download the Gmail message and stream it to your client.
This is Aqueduct(Dart) sample code:
Have a dedicated route for attachments (tempToken&fileName is optional, also contentType can be derived from attachment data):
..route('/attachments/:tempToken/:msgId/:attachmentId/:fileName').link(()
=> AttachmentsController(ctx))
The controller essentially loads an attachment by msgId&attachmentId and gives its content to a client:
#Operation.get('tempToken', 'msgId', 'attachmentId', 'fileName') Future<Response> getAttachment(
#Bind.path('tempToken') String tempToken, //
#Bind.path('msgId') int msgId,
#Bind.path('attachmentId') String attachmentId,
#Bind.query('contentType') String contentType) async {
...
final attachment = await mailbox.readAttachment(messageId,attachmentId);
return Response.ok(attachment)
..encodeBody = false
..contentType = ContentType.parse(contentType); }
We use Google provided Gmail API library. This is mailbox.readAttachment:
#override
Future<List<int>> readAttachment(String messageId, String attachmentId) async => (await _gmail.users.messages.attachments.get('me', messageId, attachmentId)).dataAsBytes;

Microsoft outlook doesn't shows German umlauts

I have an email send through SMTP which contains some German characters (umlauts). The encoding used is 'UTF-8', but the content is not displaying correctly.
But when I choose the 'view source' in outlook app (by right click), the result shows all the umlauts. See in high lighted.
How to solve this problem? The content of the mail is created programmatically through the following code.
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessage.setContent("<html><head><meta charset=\"UTF-8\"></head><body>Hallo Saju Paul,<p>Wir.....", "text/html");
helper.setTo("sender#sender.com");
helper.setSubject("Setze dein Passwort zurück");
helper.setFrom("undefined#variables.env");
mailSender.send(mimeMessage);
where mailSender is
org.springframework.mail.javamail.JavaMailSender
How to solve this problem?

Javamail Content-Type

I'm trying to send an Email via javamail adding embedded Images and an Outlook Invation which should be displayed showing up the buttons to accept/decline .... To make the buttons show up, i have to set the Content-Type of the MimeMultipart to related.
MimeMultipart multipart = new MimeMultipart("related");
Once this is done, the embedded Pictures wont show up again.
To Display the embedded images it should be alternative.
I have send myself a Mail from Outlook containing an Image as well as a invation to a meeting.
When I check the header there, it says:
Content-Type: multipart/related;
boundary="_005_CCF531A072806F489D02A6DD2CF322A01D88EEA2de35s004hst42wp_";
type="multipart/alternative"
I have already tried to set the Content-Type adding Parameters (type, charset ...) but it seems like their just getting ignored when sending the message. Here is the Method which I am calling to create the Message Part:
private Message generateMessage() throws Exception
{
Configuration conf = Configuration.getInstance();
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", conf.getProperty(Configuration.MAIL_SERVER));
// Get session
Session session = Session.getDefaultInstance(props, null);
// Create the message
Message message = new MimeMessage(session);
// Fill its headers
message.setSubject(this.subject);
message.setFrom(new InternetAddress(fromEmail));
Address[] replyTo = new Address[]{new InternetAddress(replyEmail)};
message.setReplyTo(replyTo);
// Create a related multi-part to combine the parts
MimeMultipart multipart = new MimeMultipart("related");
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
multipart.addBodyPart(messageBodyPart);
// ADD IMAGES
multipart = attachImages(multipart);
// ADD CALENDAR-FILE
multipart = attachCalendarFile(multipart);
// Set Content-Type
ContentType ct = new ContentType(message.getContentType());
ct.setParameter("charset", "utf-8");
ct.setParameter("type", "multipart/alternative");
// Set Multipart-Content to Message including the Content-Type
message.setContent(multipart, ct.toString());
return message;
}
The output of message.writeTo(System.out); is the following:
From: mail#sender.com
Reply-To: noreply#recipient.com
Message-ID: <1150322817.1.1397725164700.JavaMail.User#MacBooks-mailserver.local>
Subject: test
MIME-Version: 1.0
Content-Type: multipart/related;
boundary="----=_Part_0_72769750.1397725164655"
------=_Part_0_72769750.1397725164655
Is there any chance to make it work with embedded images AND invations?
Thanks in advance!
There's three types of multiparts, each used for a different purpose. In some cases you might need to use all three. For example, a message with a calendar attachment, html content using images, and equivalent plain text content, might have a structure such as this:
multipart/mixed
multipart/alternative
text/plain
multipart/related
text/html
image/jpeg
text/calendar
Google search led me here, so for future searchers:
#bill-shannon is of course correct. However, please save yourself the trouble of figuring out the low level Mime RFC stuff, and just use something like Simple Java Mail (open source) which figures out which structure suits best based on the input you provide. You can interactively explore all the possible structures Simple Java Mail can come up with. Disclaimer: I maintain this library (but I actually came across this SO question in my research into including voting buttons in emails for Outlook :) )
In your case you would use the following. First produce a Calendar content string, using something like ical4j:
Calendar icsCalendar = new Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
(..) // add attendees, organizer, end/start date and whatever else you need
// Produce calendar string
ByteArrayOutputStream bOutStream = new ByteArrayOutputStream();
new CalendarOutputter().output(icsCalendar, bOutStream);
String yourICalEventString = bOutStream.toString("UTF-8")
Then use Simple Java Mail's email builder to set the Calendar content alongside everything else such as images:
Email email = EmailBuilder
.startingBlank()
.withCalendarText(CalendarMethod.REQUEST, yourICalEventString)
.everythingElseLikeImagesHeadersAttachmentsEtcEtc()
.buildEmail();
Then send using the mailer builder:
MailerBuilder
.withSMTPServer("server", 25, "username", "password")
.buildMailer()
.sendMail(email);
Then depending on whether you provided text, html attachments or other things, Simple Java Mail will select the appropriate Mime structure with mixed/related/alternative parts.

sending mail usingsprings with html content as text

by using above code i send the mail, body with normal text. now i want to send the mail with html content as body any suggestions appriciate.
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("xxxxxxxxxxxx#gmail.com");
message.setTo("xxxxxxx.yyyyyy#gmail.com");
message.setSubject("Hi");
message.setText("Welcome to FoodeeBuddee");
javaMailSender.send(message)
}
You can create mail using velocity template refer to 24.3.2 Creating email content using a velocity template library for more doc detail.

Resources