I'm trying to setup Javax.mail to work with sendpulse smtp server (actually had different prob with other also).
currently it's always just hangs here System.out.println("\n\n 3rd ===> Get Session and Send mail");. No exceptions (even i setup a timeouts), nothing.
Also, debug shown me that transport contains login value as mypcname#smtp-pulse.com, which is not right. and the defaultPort = 465 (instead of 2525 set by me in properties)
smtp serve configured by input string smtp-pulse.com,2525,maemail#yahoo.com,mypass ->
the current method to send (tried a lot of different options):
public SMTPresponce SendHtmlEmail(String receipient){
Integer timeout = 20000;
logger.info("Sending to: "+receipient);
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.setProperty("mail.transport.protocol", "smtp");
mailServerProperties.setProperty("mail.smtp.host", accountSMTP.getHost());
mailServerProperties.setProperty("mail.smtp.port", accountSMTP.getPort());
mailServerProperties.setProperty("mail.smtp.starttls.enable", "true");
mailServerProperties.setProperty("mail.smtp.ssl.enable", "true");
mailServerProperties.setProperty("mail.smtp.ssl.trust", "*");
mailServerProperties.setProperty("mail.smtp.auth", "true");
mailServerProperties.setProperty("mail.smtp.timeout", timeout.toString());
mailServerProperties.setProperty("mail.smtp.connectiontimeout", timeout.toString());
try {
System.out.println("\n\n 2nd ===> get Mail Session..");
getMailSession = Session.getDefaultInstance(mailServerProperties, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(accountSMTP.getLogin(), accountSMTP.getPassword());
}
});
generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receipient));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("test#mail.com"));
try {
generateMailMessage.setFrom(new InternetAddress(messageMy.getFinalFrom(), messageMy.getReply_to()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receipient));
generateMailMessage.setSubject(messageMy.getFinalTopic());
generateMailMessage.setContent(messageMy.getFinalBody(), "text/html; charset=utf-8");
// Send message
// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
return SMTPresponce.SEND_SUCCESS;
}
catch (AuthenticationFailedException ex){
return SMTPresponce.AUTH_FAIL;
}
catch (MessagingException mex) {
logger.error(mex.getCause());
mex.printStackTrace();
if(mex.getCause().toString().contains("Connection timed out"))
return SMTPresponce.TIMEOUT;
return SMTPresponce.SEND_FAIL;
}
}
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
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 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);
im facing some problems with Lotus server.
The guy that is in charge of the server is telling me that the configuration is ok, but i cant send mail with html body with his lotus server.
The error i get is : “554 Relay rejected for policy reasons.”
When i tried on my pc, i used smpt.gmail.com and worked like a champ. So i believe is not a code problem and the issue is with the server configuration.
Is there a problem with javaMail and Lotus? is it a common issue? (in one blog some guy was saying that it can not be possible to send html but i cant believe that)
My code just in case,
public void sendEmail(String toEmailAddr, String subject, String issue) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress toAddress = null;
InternetAddress toAddress2[] = null;
Transport t = null ;
try {
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(issue, "text/html");
mp.addBodyPart(htmlPart);
simpleMessage.setContent(mp);
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
toAddress = new InternetAddress(toEmailAddr);
toAddress2 = new InternetAddress [1];
toAddress2[0] = toAddress;
} catch (AddressException e) {
// TODO LOG
e.printStackTrace();
}
try {
simpleMessage.setRecipients(RecipientType.TO, toAddress2);
simpleMessage.setSubject(subject);
t = mailSession.getTransport("smtp");
if(userPwd==null)
userPwd = "";
t.connect(host, userName, userPwd);
t.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
// TODO LOG
}finally{
try {
t.close();
} catch (MessagingException e) {
// TODO LOG
}
}
}
Regards.
SMTP on the Domino server has most likely been set up to only allow relay by certain hosts - therefore the error message 554 Relay rejected for policy reasons.
You should talk to the admin and have him change the configuration to allow relay by other hosts. This is configured in a configuration document in the Router/SMTP -> Restrictions and Controls -> SMTP Inbound Controls section. More information on SMTP inbound relay controls is available here:
http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.help.domino.admin.doc%2FDOC%2FH_SETTING_INBOUND_RELAY_CONTROLS_STEPS.html
i had the same problem and solved it. The FROM part was "me#example.com" and changed it to "myname#mydomain.com" and it began to send
May require Secure Connection(SSL), Use the following properties to connect mail server supporting smtp protocol:
properties.put("mail.smtp.socketFactory.port", "SMTP_PORT");
properties.put("mail.smtp.host", "SMTP_SERVER_HOST_NAME_OR_IP");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
I am attempting to send an email using Java. From reading, I have found that if I use gmail as the host I can do this for free & it should work, is that correct.
So I have my code below, & I am attempting to send an email from myself to my friends emails(the emails in my code below have been altered for privacy) but I get an exception thrown when I go to send/transfer the email (at the line Transport.send(msg);)
The output/exception thrown is:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
Should have succeeded: false
What do you think I am doing wrong?
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String username = "myaccount#gmail.com";
String password = "xxxxxxx";
return new PasswordAuthentication(username, password);
}
}
public class SendEmail
{
public SendEmail()
{
}
public static boolean sendEmail( String from, String to[], String subject, String body )
{
try
{
boolean debug = false;
// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com" ); // "smtp.jcom.net");
props.put("mail.smtp.auth", "true");
// create some properties and get the default Session
// Session session = Session.getDefaultInstance(props, null);
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
addressTo[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if
// you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(body, "text/plain");
System.out.println( "1" );
Transport.send(msg);
System.out.println( "2" );
}
catch (Exception e)
{
System.out.println( e );
return false;
}
return true;
}
public static void main(String args[])
{
boolean res = SendEmail.sendEmail( "myaccount#gmail.com", new String[] {"x#y.com", "y#x.com.au"},
"Test", "Did it work?" );
System.out.println( "Should have succeeded: " + res );
}
}
Google is your friend. Check this site: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
Gmail only accepts secure connections using TLS, but you're using the standard non-secure authentication.
Try with the port 465 (found here)