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);
Related
I am writing an email client to send email using yahoo SMTP server.
Getting error: com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
Passed Authentication but throwing 554 while sending email:-
public static void main(String[] args) {
final String fromEmail = "myyahoo#yahoo.com"; //requires valid id
final String password = "xxxxxxx"; // correct password for gmail id
final String toEmail = "test.existing#gmail.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.mail.yahoo.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "Required"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
System.out.println("Calling getPasswordAuthentication");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
System.out.println("After getPasswordAuthentication");
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"My First TLSEmail Testing Subject", "My first email client. TLSEmail Testing Body");
}
Output:-
TLSEmail Start
Calling getPasswordAuthentication
After getPasswordAuthentication
Message is ready
com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2358)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1823)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1300)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at EmailUtil.sendEmail(EmailUtil.java:48)
at MyEmail.main(MyEmail.java:38)
What is the problem here.
Here is class EmailUtil:
public class EmailUtil {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply#example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply#example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This client sends email using gmail SMTP server.
If you read here https://serversmtp.com/port-outgoing-mail-server/ and also here https://getmailspring.com/setup/access-yahoo-com-via-imap-smtp
You will notice that yahoo uses port 465 and in your code i see 587
When I am trying to send a mail from "smtpout.asia.secureserver.net", it is sending from localhost instead of the "secureserver" host.Below is the code :
Properties props = new Properties();
props.put("mail.smtp.host","smtpout.asia.secureserver.net");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxx#xxxxx.net","xxxxx");
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
//send message
Transport.send(message);
System.out.println("message sent successfully");
}
catch (MessagingException e) {throw new RuntimeException(e);}
Debug :
com.sun.mail.smtp.SMTPSendFailedException
550 <narasimhatejav#teja> Sender Rejected - MAILFROM must be a valid domain. Ensure the mailfrom domain: "teja" has a valid MX or A record.
DEBUG SMTP: got response code 550, with response: 550 <narasimhatejav#teja> Sender Rejected - MAILFROM must be a valid domain. Ensure the mailfrom domain: "teja" has a valid MX or A record.
But if i change the host to "smtp.gmail.com" it is working fine.
Change the Java mail Jar to v1.5+ and add void javax.mail.internet.MimeMessage.setFrom(String address) function
It's sending from localhost because you made most of the common JavaMail mistakes.
The MAILFROM problem is because the host name or name service is misconfigured on your machine. As a workaround you can set the mail.smtp.localhost property.
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 need to send at least 200 messages from a stretch. When the program starts, send mail successfully to 15 or 17, then I get this error:
MESSAGE ERROR:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
What I can do?
CODE JAVA
public void mandarEmail(String correos, String mensaje, String asunto) {
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("docemail#usmp.pe", "docpass");
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("USMP - FN <documentos-fn#usmp.pe>"));
message.setSubject(asunto);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(correos));
message.addRecipients(Message.RecipientType.BCC, new InternetAddress[]{new InternetAddress("ivan_pro_nice#hotmail.com")});
message.setContent(mensaje, "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect("docemail#usmp.pe", "docpass");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
That's the server you're connecting to, and not a client issue. Here's a doc on how to parse SMTP codes from the server.
A mail server will reply to every request a client (such as your email
program) makes with a return code. This code consists of three
numbers.
In your case, you're getting 421.
You probably need to pay for a "business" account from your mail server vendor so they'll let you send more email.
if you want to send single email to 200 clients. Than u can add an array of reciever's email addresses of size upto 50.
but i you want to send different msg for each email. Then you can create a new connection to email server with a counter that counts send emails as well as it counts 15 it should create a new connection.
to test your code use mailtrap.io
I have below code to send an email to my gmail.
public class Mainclass {
public static void main(String args[]){
String host = "smtp.gmail.com";
String from = "from_address#fdsl.com";
String to = "mymail#gmail.com";
// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", true);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("username", "mymail#gmail.com");
props.put("password", "mypassword");
// Get session
Session session = Session.getInstance(props);
try {
// Instantiate a message
Message msg = new MimeMessage(session);
// Set the FROM message
msg.setFrom(new InternetAddress(from));
// The recipients can be more than one so we use an array but you can
// use 'new InternetAddress(to)' for only one address.
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
// Set the message subject and date we sent it.
msg.setSubject("Email from JavaMail test");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is the text for this simple demo using JavaMail.");
// Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
But when i run the code i always get below the exception.
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
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)
at Mainclass.main(Mainclass.java:66)
Am i missing anything here? My password is correct. Please help me.
Thanks!
Have you set the host correctly ? Also, I don't see which ports are you using to connect. Have you set the correct ports? Is TLS the correct auth encryption for gmail ?
Please see the attached config:
'SMTP::TLS',
Host => 'smtp.gmail.com',
Port => 587,
User => 'username#gmail.com',
Password => 'password'