Sending email using godaddy account using java - java

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

Related

Postfix returning Invalid Addresses; 454 <to#domain.com>: Relay access denied

I'm using a pre-configured Postfix server and interacting with it using JavaMail. I am trying to send email notifications to any external domain that may request it.
Here is the java method to send a test email:
public void TestEmail() {
String to = "to#domain.com";
String from = "noreply#hostdomain.com";
final String username = "user";
final String password = "password";
String host = "xxx.xxx.xxx.xxx";
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");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setContent("This is a test email", "text/html");
Transport.send(message);
System.out.println("The test message was sent!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
When I run the method that contains the JavaMail code, I get
generalError: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 454 4.7.1 <to#domain.com>: Relay access denied
I was able to test outgoing mail from the Postfix server using
echo "This is the body" | mail -s "This is the subject" to#domain.com
and did receive the email in the testing inbox.
I'm not 100% sure what all the settings are on the Postfix server, but I am suspecting that is where the issue is, but I'm not familiar enough with it to start digging around and changing things all willy-nilly.
EDIT:
I removed the Authenticator() set up from the Session creation and replaced Transport.send() with recommended code block
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
The entire new set of code is:
String host = "xxx.xxx.xxx.xxx";
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");
Session session = Session.getInstance(props, null);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setContent("This is a test email", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("The test message was sent!");
} catch (MessagingException e) {
System.out.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e);
}
}
This has changed the error message I am receiving to: Unrecognized SSL message, plaintext connection?
Solved
Solution: The Java code was not the issue. The Postfix server was not configured to accept emails originating from a non-local IP/host. The IPs were added to the main.cf in the mynetworks variable.
This article has more information.
First, get rid of the Authenticator as described in the JavaMail FAQ. That will ensure that it's really trying to authenticate to the server. Turn on JavaMail session debugging to make sure it is authenticating.
Note that you can replace
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
with
Transport.send(message, username, password);
You can get rid of the mail.smtp.auth setting, but keep the other properties.
Make sure you're using the most current version of JavaMail.
If it still doesn't work, the article above may provide some clues as to how to change the Postfix configuration.

Error when sending email via Java Mail API?

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();}
}

Why Java MailSender does not Recognize the destination email?

I have a MailSender class that has 2 methods:
private Session createSmtpSession(final String fromEmail, final String fromEmailPassword) {
final Properties props = new Properties();
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty ("mail.transport.protocol", "smtp");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, fromEmailPassword);
}
});
}
public void sendEmail(String subject, String fromEmail, String fromEmailPassword, String content, String toEmail){
Session mailSession = createSmtpSession(fromEmail, fromEmailPassword);
mailSession.setDebug (true);
try {
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject (subject);
message.setFrom (new InternetAddress (fromEmail));
message.setContent (content, "text/html");
message.addRecipient (Message.RecipientType.TO, new InternetAddress (toEmail));
transport.connect ();
transport.sendMessage (message, message.getRecipients (Message.RecipientType.TO));
}
catch (MessagingException e) {
System.err.println("Cannot Send email");
e.printStackTrace();
}
}
ok, The way the above code works is like this:
I have personal gmail myEmail#gmail.com & if I want to send msg to destination email like aa#xyz.com from myEmail#gmail.com, then I need to call sendEmail(subject, "myEmail#gmail.com", fromEmailPassword, content, "aa#xyz.com");
But recently I bought VPS from Godaddy & I am using Godaddy Email (info#mydomain.com) so I want to send smg to destination email like aa#xyz.com from info#mydomain.com, then I need to call sendEmail(subject, "info#mydomain.com", fromEmailPassword, content, "aa#xyz.com");
However I got error cos Godaddy using port 25
So I changed the code in createSmtpSession as following:
props.setProperty ("mail.host", "smtp.mydomain.com");
props.setProperty("mail.smtp.port", "" + 25);
However, this time I got other problem
DEBUG SMTP: Sending failed because of invalid destination addresses
RSET
250 2.0.0 OK
DEBUG SMTP: MessagingException while sending, THROW:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 <aa#xyz.com> Recipient not found. <http://x.co/irbounce>
Clearly the aa#xyz.com is actually existed, but why the error saying Recipient not found.
SO How to fix this issue?
I need to look at the outgoing (SMTP) server (like smtpout.secureserver.net) in Godaddy Email & now it working fine
props.setProperty ("mail.transport.protocol", "smtps");
props.setProperty ("mail.smtps.host", "smtpout.secureserver.net");
props.setProperty("mail.smtps.auth", "true");
props.setProperty("mail.smtps.port", "" + 465);

Error while sending mails using smtp

I need to send mail from my gmail account to another. I used the following code.
String fromaddress = "xxx#gmail.com";
String password = "yyy";
String hostname = "smtp.gmail.com";
String hoststring = "mail.smtp.host";
String toaddress = "yyy#gmail.com";
String emailcontent;
Properties properties = System.getProperties();
properties.setProperty(hoststring, hostname);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromaddress));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
message.setSubject("hi");
emailcontent = "hi...";
message.setText(emailcontent);
System.out.println(emailcontent);
Transport.send(message);
System.out.println("Sent....");
}catch (MessagingException mex)
{
mex.printStackTrace();
}
But i get the error as follows...
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25
How am i to solve this. Can you please help me out.
public static void sendEmail(Email mail) {
String host = "smtp.gmail.com";
String from = "YOUR_GMAIL_ID";
String pass = "YOUR_GMAIL_PASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set sender
message.setFrom(new InternetAddress("Senders_EMail_Id"));
// Set recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));
// Set Subject: header field
message.setSubject("SUBJECT");
// set content and define type
message.setContent("CONTENT", "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mex) {
System.out.println(mex.getLocalizedMessage());
}
}
}`
I think this should do the trick.
I think you need to change the port no. 25 to 587
you can get help from
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
gmail setting help link:
http://gmailsmtpsettings.com/
Just adding few more tweaks to the question above:
Change the port to 465 to enable ssl sending.
I don't think above code will work, as you need to have an authenticator object too. As smtp also requires authentication in case of gmail.
You can do something like:
Have a boolean flag,
boolean authEnable = true; //True for gmail
boolean useSSL = true; //For gmail
//Getters and setters for the same
if (isUseSSL()) {
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
}
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com", "xyz"));
}
};
if (isAuthEnable()) {
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}

Send image in Email Body using Java

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).

Categories