I have been able to send Image as an Attachment in an Email using Java. I am now trying to send the same image in the Email Body Like this:
public static void main(String[] args) throws NoSuchProviderException, MessagingException {
System.out.println("Sending mail...");
Properties props = new Properties();
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.user", "mysusername");
props.setProperty("mail.smtp.password", "mypassword");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("myaddress#gmail.com"));
message.setContent
("<h1>This is a test</h1>"
+ "<img src=\"C:/Users/pc/Desktop/Photos/Shammah.PNG\">",
"text/html");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("receiver#simbatech.biz"));
transport.connect();//This is line 46
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
I am getting this output:
Sending mail...
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at image.in.body.ImageInBody.main(ImageInBody.java:46)
Java Result: 1
Why is authentication failing while I am using the correct username and Password for My Gmail account?
see the below code may be use full
class SimpleMail2 {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail...");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sender#gmail.com","password");
}
});
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("sender#gmail.com"));
message.setSubject("HTML mail with images");
message.setRecipient(Message.RecipientType.TO, new InternetAddress("receiver#gmail.com"));
message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Raghava chary</H1>" + "<img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
try {
messageBodyPart = new MimeBodyPart();
InputStream imageStream = SimpleMail2.class.getClass().getResourceAsStream("/ab/log.gif");
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(imageStream), "image/gif");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and add org.apache.commons.io.jar.zip and axiom-api-1.2.6.jar and add mail.jar and activation.jar
You need to declare your images like this :
<img src="cid:unique-name-or-id" />
Load images as MimeBodyPart and match the unique-name-or-id with the FileName of the MimeBodyPart.
Create a multipart body with content-disposition inline and encode in base64 your image.
Check this SO for some details (in Python) Sending Multipart html emails which contain embedded images
First, see this JavaMail FAQ entry of common mistakes.
Then, see this JavaMail FAQ entry with sample code for connecting to Gmail.
Note that there is no "mail.smtp.password" property. Since you're not supplying a password, authentication is failing.
Another common mistake (bit me today): the Content-ID header for the image must be in <angle brackets>. Failure to do so will break some mail programs (gmail, OS X 10.10) but not others (Outlook, iOS <= 8.1).
Related
How do I submit a pdf file to a generic e-mail from Java application?
You can Send E-Mail with PDF file as Attachment using reference of this -
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendMailWithAttachment
{
public static void main(String [] args)
{
String to="XYZ#abc.com"; //Email address of the recipient
final String user="ABC#XYZ.com"; //Email address of sender
final String password="xxxxx"; //Password of the sender's email
//Get the session object
Properties properties = System.getProperties();
//Here pass your smtp server url
properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password); } });
//Compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Aleart");
//Create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//Create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "YourPDFFileName.pdf";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//Create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//Set the multiplart object to the message object
message.setContent(multipart );
//Send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
You can also refer to JavaTPoint
delete the part :
//Here pass your smtp server url
properties.setProperty("mail.smtp.host",
"mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
And paste the code below :
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.socketFactory", "587");
props.put("mail.smtp.port", "587"); //587
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
I want to get all unread emails from server and send each message to another email. When I send each unread email (Using HostGator), after sending few mails (30-40) an error occurs as I mentioned. This is my sending method. What can i do? I checked with smtp port 25,465,587. but none of them worked. Same error appears. :/ if any one knows how to handle it please let me know. Thank you..
email send method:-
public static void send(String sub,final String user, final String pass, String toMails) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "gator.hostgator.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipients(Message.RecipientType.TO, toMails);
message.setSubject(sub);
message.setText("-Body-");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("-Body-");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
}
This is error message :-
I got following error when trying to send email via Java Mail API? What does this error mean?
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2210)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Here is my code, i set all parameters (from, to , subjects and attachments)
public static void send(MailUtil mailUtil) throws MessagingException {
MimeMessage message = new MimeMessage(session);
if (props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER) != null) {
message.setFrom(new InternetAddress(props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER)));
} else {
message.setFrom(new InternetAddress(mailUtil.getFrom()));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailUtil.getTo()));
if (mailUtil.getBcc() != null && mailUtil.getBcc().trim().length() > 0) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailUtil.getBcc()));
} else {
message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(""));
}
message.setSubject(mailUtil.getSubject(), "UTF-8");
// Check for files list and attach them.
if (mailUtil.attachmentFiles != null && mailUtil.attachmentFiles.size() > 0) {
Multipart multipart = new MimeMultipart();
// Set content.
BodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(mailUtil.getContent(), "text/plain; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// Attach files.
for (File file : mailUtil.attachmentFiles) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
//message.setContent("<h1>Hello world</h1>", "text/html");
message.setContent(mailUtil.getContent(), "text/html; charset=UTF-8");
}
Transport.send(message);
}
I just think is there any problem with my paramters?
Belows is my configuration
mail.smtp.port=465
mail.smtp.starttls.enable=true
mail.smtp.auth=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.timeout=25000
mail.smtp.host=smtp.gmail.com
mail.username = username#gmail.com
mail.password = mypassword
mail.sender = sender#gmail.com
mail.receiver = receiver#gmail.com
mail.subject = mysubject
I am using google mail server! I dont' think there is problem there!
Belows is session initiation
final String userName = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_USERNAME);
final String passWord = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_PASSWORD);
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,
passWord);
}
});
I believe it absolutely relates to server configuration.
When I change the port configuration from 465 to 587, it solves my problem!
Anyway, thank you guy for your help!
Your code and configuration contain many of these common mistakes. In particular, the use of Session.getDefaultInstance may mean you're not using the configuration you think you're using. If fixing that doesn't solve your problem, post the JavaMail session debug output.
I'm not sure why you use a "mail" object to setup the connection properties, instead try this, it should work, I've tested myself:
private Properties props;
props = System.getProperties();
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.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS HERE"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECEIVER EMAIL ADDRESS HERE"));
message.setSubject("SUBJECT");
message.setText("THE EMAIL TEXT");
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
}
I am trying to send emails using my godaddy account in java. Below is my code.
Properties props = System.getProperties();
props.put("mail.transport.protocol","smtp" );
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.smtp.host","smtpout.secureserver.net");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
props.put("mail.debug","true");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
Authenticator auth = new SMTPAuthenticator();
Session session=Session.getInstance(props,auth);
session.setDebug(true);
// -- Create a new message --
Transport transport=session.getTransport();
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(""email#domain.com));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("email#domain.com", false));
msg.setSubject("subject");
msg.setText("Message");
transport.connect();
Transport.send(msg);
transport.close();
While executing I'm getting the below Exception.
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtpout.secureserver.net , 465; timeout -1;
nested exception is:
java.net.UnknownHostException: smtpout.secureserver.net
PS:When i use gmail account for authentication its working fine and email sent successfully. When i use godaddy account the exception throws.
Please guide me how to solve this issue...
Thanks in advance...
My configuration in SpringBoot (replace domainname.com to your domainname)
spring:
mail:
host: smtpout.secureserver.net
port: 465
username: info#domainname.com
password: password
protocol: smtp
properties.mail.smtp:
auth: true
ssl.enable: true
ssl.trust: "*"
Also I had to add mimeMessageHelper.setFrom("info#domainname.com"); before sending the mail (else it was taking my system name and gave an error) and this setup worked.
Here is complete method that is working absolutely fine for me (I have also used an attachment in the message) :
private void sendUsingSmtp(MailDetail mailDetail) {
Properties props = new Properties();
props.put("mail.host", "smtpout.secureserver.net");
props.put("mail.port", "465");
props.put("mail.username", "info#domainName.com");
props.put("mail.password", “password”);
props.put("mail.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.trust", "*");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("info#domainName”, “password");
}
});
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress("info#domainName.com", false);
msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(“targetEmail#gmail.com"));
msg.setSubject("Test Subject.");
msg.setContent("Test Content.", "text/html");
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Test Content.", "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile("/var/tmp/abc.txt");
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JavaMail SSL with no Authentication trust certificate regardless
MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
requires javax.mail 1.5.2 and greater
i peek in many mail api like gmail etc. they send html content by mail api ,almost a form with some widgets. I am also trying to do that but whenever in try this with html content , its giving me error
String to="xyz#gmail.com";//change accordingly
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz.com","xyz");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("hellofacebook180#gmail.com"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(input);
message.setContent("<h1>sending html mail check</h1>","text/html" );;
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {throw new RuntimeException(e);}
return "massage sent";
please help how can I sent Html content with mail api
Email clients (Gmail, etc.) do not allow external CSS files. There is nothing you can do about it.