I am developing an app where I need to set image in a header and footer of a mail. I saw method setHeader(String header-name, String header_value) but when I put into it a path to my image I don't get anything.
This is my code:
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg");
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
As you can see in part
msg.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg")
I put some key and value which is path to my Image which I want to set into header. But nothing happens. Can someone help me?
The word "header" in a MIME message refers to a section of the message that has "key: value" fields. This section is called "header" because it's transmitted before the "body" content of the message. The headers are for things like "Date", "Subject", "Content-Type".
The word "header" does not refer to a graphical header that would be visible on the screen or when printed. To add this type of a header, you have to modify the content of the message. In your program, that's stored in the htmlBody variable.
I don't think you can simply modify htmlBody to add a header to it, without knowing how it is structured. In the general case, the page header has to be incorporated in the HTML message design from the start.
Related
So I have the problem with the Javamail where if I send an attachment in the mail the body disappears. When I don't send an attachment with the mail i can just see the body.
My GMailSender.java:
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
_multipart = new MimeMultipart();
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setText(body);
message.setDataHandler(handler);
if(_multipart.getCount() > 0)
message.setContent(_multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}
public void addAttachment(String filename) throws Exception
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
My MainActivity.java
Button bt_send = findViewById(R.id.Alert);
bt_send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
BackgroundMail bm = new BackgroundMail(context);
bm.setGmailUserName("***#gmail.com");
bm.setGmailPassword("******");
bm.setMailTo(to);
bm.setFormSubject(value + " DOC/" + mTvResult.getText().toString());
bm.setFormBody("Document Nummer:\n" + mTvResult.getText().toString() + "\n \nDocument Type:\n" + value);
if (images.size() > 0) {
for (Object file : images) {
bm.setAttachment(file.toString());
}
}
bm.setSendingMessage("Loading...");
bm.setSendingMessageSuccess("The mail has been sent successfully.");
bm.send();
}
});
So how can i add an attachment while still being able to see the body itself?
Thanks in advance!
It looks like you copied GMailSender from someone else. You should start by fixing all these common mistakes.
You never call the addAttachment method. (Note that you could replace that method with the MimeBodyPart.attachFile method). Please remember to post the code that you're actually using.
The key insight that you're missing is that for a multipart message the main body part needs to be the first body part in the multipart. Your call to Message.setContent(_multipart); overwrites the message content that was set by your call to message.setDataHandler(handler);, which also overwrote the content set by your call to message.setText(body);.
Instead of setting that content on the message, you need to create another MimeBodyPart, set the content on that MimeBodyPart, and then add that MimeBodyPart as the first part of the multipart.
I am using MultipartFile to send an email with multiple attachments. my code is working fine but I am storing each file in my project then I am attaching. I don't want to store that file anywhere instead I want the file directly send to the recipients.
My code is,
Controller:
#RequestMapping(value="/sendEmailAttachment",method=RequestMethod.POST)
public #ResponseBody Response sendEmail(#RequestParam("file") MultipartFile[] file,#ModelAttribute Email email) {
SendEmail mail = new SendEmail();
return mail.sendEmail(email,file);
}
Service:
public Response sendEmail(Email email,MultipartFile[] attachFiles) {
username = email.getUsername();
password = email.getPassword();
switch (email.getDomain()) {
case "1and1.com":
host = "smtp.1and1.com";
break;
case "gmail.com":
host = "smtp.gmail.com";
break;
case "yahoo.com":
host = "smtp.mail.yahoo.com";
break;
case "rediffmail.com":
host = "smtp.rediffmail.com";
break;
default:
host = "smtp.1and1.com";
username="support#gmail.com";
password="************";
break;
}
props.put("mail.smtp.host", host);
Response response = new Response();
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);
InternetAddress[] myToList = InternetAddress.parse(email.getTo());
InternetAddress[] myBccList = InternetAddress.parse(email.getBcc());
InternetAddress[] myCcList = InternetAddress.parse(email.getCc());
// Set From: header field of the header.
message.setFrom(new InternetAddress(email.getUsername()));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,myToList);
message.setRecipients(Message.RecipientType.BCC, myBccList);
message.setRecipients(Message.RecipientType.CC, myCcList);
// Set Subject: header field
message.setSubject(email.getSubject());
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setContent(email.getBody(), "text/html");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
if(attachFiles != null && attachFiles.length > 0){
for (MultipartFile filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
attachPart.attachFile(filePath.getOriginalFilename());
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// Send the complete message parts
message.setContent(multipart);
// Transport.send(message, message.getAllRecipients());
Transport.send(message);
response.setStatus(200);
response.setMessage("Sent Email Successfully");
} catch (MessagingException e) {
response.setStatus(-1);
response.setMessage(""+e);
response.setObject(e);
e.printStackTrace();
}
return response;
}
Here I have witten like,
filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
attachPart.attachFile(filePath.getOriginalFilename());
I dont want to transfer/save file into the project and attach, I want to send the file directly. any help will appreciated.
Try this:
attachPart.setContent(filePath.getBytes(), filePath.getContentType());
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);
In my case, the answer of #Bill Shannon give me the error "java.io.IOException: “text/plain” DataContentHandler requires String object, was given object of type class [B"
I modified the code like this :
DataSource ds = new ByteArrayDataSource(filePath.getBytes(), filePath.getContentType());
attachPart.setDataHandler(new DataHandler(ds));
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);
If you are using Spring, then you can use JavaMailSenderImpl and MimeMessageHelper:
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
helper.addAttachment("fileName", filePath);
mailSender.send(mailMessage);
List<MultipartFile> attachments = /* this will be input for multiple files */
Multipart multipart = new MimeMultipart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(/* email content */, "text/html");
multipart.addBodyPart(mimeBodyPart);
for(int i = 0 ; i < attachments.size() ; i++) {
mimeBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachments.get(i).getBytes(), attachments.get(i).getContentType());
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(attachments.get(i).getOriginalFilename());
multipart.addBodyPart(mimeBodyPart);
}
email.setContent(multipart);
I'm trying to send a email with a Table in string with RTF, but when I check the email the message body, the table lost the format, so I wondering what I'm doing wrong, this is the following chunk of code to send and email
public static void send(String asunto, String texto, String emailDestinatario){
final String username = "myemail#gmail.com";
final String password = "mypass";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse( emailDestinatario));
message.setSubject(asunto);
message.setText(texto);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
what others configurations I need to send and email and recogniz me the format of table?
This is a document example to send via email
I get something like that(the table lost the format)
TARIFAS EMPLEADOS
TARIFA
IVA
TOTAL
EMPLEADOS HASTA $150.000.000
94,000
15,040
109,040
EMPLEADOS MAYOR DE $150.000.000
160,000
25,600
185,600
Have you tried something like :
MimeMessage message = new MimeMessage(sesion);
.
.
.
//Config your message....
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("RTF HTML TEXT", "text/html");
mp.addBodyPart(htmlPart);
message.setContent(mp);
Transport.send(message);
I currently have a program that sends users an email based on their information in my database. The email is built out in html and sends to the users email as a content type text/html. I want to try and see if I could somehow send this message to their phone using the email format ###########domain.com.
Obviously phones cant receive an HTML message, so I tried this:
-Removed the html and sent pure text, this did work, however for Verizon (the only service provider I tested) the text got cut off and the full message never sent. I only received the first part of the message.
Then I wondered if it was possible to somehow "screenshot" the html message and simply send the picture of the html display to the phone.
Here is my current code to send an email:
public static void email(String content, String address) {
final String username = "email";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
Address[] a = InternetAddress.parse("myemail");
message.setReplyTo(a);
message.setHeader("From: ", "Movie Alert");
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(address));
if (ShowFinder.showsFound > 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Shows Found!");
else if (ShowFinder.showsFound == 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Show Found!");
else message.setSubject("Unsubscribed");
StringBuilder sb = new StringBuilder();
sb.append(content);
message.setContent(sb.toString(), "text/html");
Transport.send(message);
System.out.println("Sent Email");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
So in conclusion I have the following questions:
-Is the reason the text got cut off because I am not sending the email properly, or because of the service provider?
-Is it possible to send a screenshot of the html display based on the html code through a text message?
Thanks!
I found a solution to send an html message to a phone! There is a jar called HTML2Image that will convert your html code into an image: https://code.google.com/p/java-html2image/
To make an image of the html you would do something like this:
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
imageGenerator.saveAsImage("hello-world.png");
Then you could send this new image like so:
Multipart mp = new MimeMultipart();
Message message = new MimeMessage(session);
MimeBodyPart mbp1 = new MimeBodyPart();
MimeBodyPart mbp2 = new MimeBodyPart();
message.setFrom(new InternetAddress("email"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
mbp1.setText(text);
mp.addBodyPart(mbp1);
DataSource source = new FileDataSource(new File("screenshot location/hello-world.png"));
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName("Screenshot.png");
mbp2.setHeader("Content-ID", "<image_cid>");
mp.addBodyPart(mbp2);
message.setContent(mp);
Transport.send(message);
I strongly suspect the text is getting cut off because of the service provider. There's probably a limit on the size of a single text message.
If you can't fit all the text you want into a short message, you might want to send a link to a web page containing all the information.
I have an application that can send mails, implemented in Java. I want to put a HTML link inside de mail, but the link appears as normal letters, not as HTML link...
How can i do to inside the HTML link into a String? I need special characters? thank you so much
Update:
HI evereybody! thanks for oyu answers! Here is my code:
public static boolean sendMail(Properties props, String to, String from,
String password, String subject, String body)
{
try
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect(from, password);
t.sendMessage(message, message.getAllRecipients());
// Cierre.
t.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
And here the body String:
String link = "ACTIVAR CUENTA";
But in the received message the link appears as the link string, not as HTML hyperlink! I don't understand what happens...
Any solution?
Adding the link is as simple as adding the text inside the string. You should set your email to support html (it depends on the library you are using), and you should not escape your email content before sending it.
Update: since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
html is the mime subtype (this will result in text/html). The default value that is used by the setText(string) method is plain
I'm just going to answer in case this didn't work for someone else.
I tried Bozho's method and for some reason the email wouldn't send when I did the setText on the message as a whole.
I tried
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
but this came as an attachment in Outlook instead of in the usual text. To fix this for me, and in Outlook, instead of doing the mbp.setContent and message.setText, I just did a single setText on the message body part. ie:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageBody,"UTF-8", "html");
With my code for the message looking like this:
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for(String str : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
message.setSubject(subject);
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageBody,"UTF-8","html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Appending "http://" before the URL worked for me.
We can create html link in the email body by using java code.In my case I am developing reset password where I should create link and send to the user through the mail.you will create one string.With in a string you type all the url.If you add the http to the that .it behaves like link with in the mail.
Ex:String mailBody ="http://localhost:8080/Mail/verifytoken?token="+ token ;
you can send some value with url by adding query string.Her token has some encrypted value.
put mailBody in your mail body parameter.
ex": "Hi "+userdata.getFirstname()+
"\n\n You have requested for a new password from the X application. Please use the below Link to log in."+
"\n\n Click on Link: "+mailBody);
The above is the string that is parameter that you have to pass to your mail service.Email service takes parameters like from,to,subject,body.Here I have given body how it should be.you pass the from ,to,subject values according to your cast
you can do right way it is working for me.
public class SendEmail
{
public void getEmail(String to,String from, String userName,String password,Properties props,String subject,String messageBody)
{
MimeBodyPart mimeBodyPart=new MimeBodyPart();
mimeBodyPart.setContent(messageBody,"text/html");
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
Session session=Session.getInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName,password);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Have You got Mail!");
message.setText(messageBody,"UTF-8","html");
Transport.send(message);
}
catch(MessagingException ex){System.out.println(ex)}
public static void main(String arg[]){
SendEmail sendEmail=new SendEmail();
String to = "XXXXXXX#gmail.com";
String from = "XXXXXXXX#gmail.com";
final String username = "XXXXX#gmail.com";
final String password = "XXXX";
String subject="Html Template";
String body = "<i> Congratulations!</i><br>";
body += "<b>Your Email is working!</b><br>";
body += "<font color=red>Thank </font>";
String host = "smtp.gmail.com";
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", "587");
sendEmail.getEmail(to,from,username,password,props,subject,body);
}
}