The program attempts to send e-mail but throws a run time exception:AuthenticationFailedException.I have used smtp protocol for sending the mail.I have used TLS.Below is my Mailsender class named SendMail.java
package com.xxx.dashboard.mail;
import java.util.Map;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.edifixio.dashboard.configuration.ConfigurationBundle;
public class SendMail {
public static void sendMail(String toAddresses, String subject, String url, String name, String email){
Map<String, String> mapdata = ConfigurationBundle.getMapdata();
final String emailId = mapdata.get("mail_id");
final String username = mapdata.get("mail_username");
final String password = mapdata.get("mail_password");
final String smtpHost = mapdata.get("mail_smtp_host");
final String smtpPort = mapdata.get("mail_smtp_port");
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
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(emailId));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toAddresses));
message.setSubject(subject);
String text = "<b>Hello "+name+",</b><br/><br/> Thank you for registering with WARM for monitoring of your URL."
+ "<br/>In order to activate your account please <b>Click Here</b><br/><br/>"
+ "Once you have activated your WARM account you can login to the WARM Dashboard using your Username "
+ ""+email+".<br/>If you are having problems with the given link, "
+ "please reply back to the following Email address: warm.xxx#gmail.com.</br>This is a system generated mail. Please do not reply to this mail.<br/><br/>Thanks and Regards<br/>WARM Admin.";
message.setContent(text,"text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String args[]) {
sendMail("sumit.ghosh#xxx.com", "Hello", "h", "Rakesh", "rakesh#gmail.com");
System.out.println("Successfully send mail to - "+toAddresses);
}
}
When I am choosing Run as Java Application from Eclipse I am getting the following error log
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at 534 5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qk9sm15826619pac.16 - gsmtp
at com.xxx.dashboard.mail.SendMail.sendMail(SendMail.java:80)
at com.xxx.dashboard.mail.SendMail.main(SendMail.java:87)
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at 534 5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qk9sm15826619pac.16 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
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)
at com.edifixio.dashboard.mail.SendMail.sendMail(SendMail.java:74)
... 1 more
I have a properties file named config.properties where I have kept the username and password,and other credentials like port no.Please find below its code:
mail_id=test#gmail.com
mail_username=test#gmail.com
mail_password=testxxx
mail_smtp_host=smtp.gmail.com
mail_smtp_port=587
ldap_provider_ip=192.168.15.50
ldap_port=1666
ldap_base=ou=users,ou=warm,dc=xxx,dc=co,dc=in
ldap_dir_context=dc=edifixio,dc=co,dc=in
ldap_security_principal=cn=Directory Manager,dc=xxx,dc=co,dc=in
ldap_security_credential=testxxx
I had this issue as well, I had to go into my gmail account settings and under Security Enable "Access for less secure apps" to fix it.
I was also trying out the simple javax mail program using the google smtp server . On receiving Authentication failed messages ,I had to goto https://www.google.com/settings/security/lesssecureapps and turn on access for less secure apps
Log in to the gmail account specified in your properties file
Click on the circle on your top right corner -> manage your google account -> security -> Less secure app access . Turn it on
Go to https://accounts.google.com/DisplayUnlockCaptcha.
Click on continue and logout of the gmail.
Test your service. Now it will establish a connection to send mails
Your code sent mail without any exceptions in eclipse on Debian OS. Are you running any firewall or anti-virus software that might be interfering with the connection attempt?
Try with these properties:
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.auth.mechanisms=login
mail.smtp.quitwait=false
mail.debug = false
mail.username=test#gmail.com
mail.password=test
mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
mail.smtp.protocol=smtps
Related
Original Post ~
I am trying to send an email through java but I am getting an error that says it couldn't connect to host, port: smtp.gmail.com, 547; timeout -1;
I am trying to send it through gmail and I have imported two jar files, which are java mail api download – https://javaee.github.io/javamail/ java activation jar download – https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
It takes forever to run and once it finally does finish it show that error.I would appreciate any help, even if it is just pointing me to a YouTube video or another post on this website. Thank you in advance.
Updated Post~
I had a comment saying to use 587 instead of 547 so I changed it but I am now getting an javax.mail.AuthenticationFailedException: Username and password not accepted error. I have googled and even looked on stack overflow and they say to change a setting in my google account but when I go to change it google is saying the setting is no longer available... it is the Less Secure app access.
I will love any thoughts or direction on how to fix this problem. I am on a Mac if anyone thinks that could be causing a problem.
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Properties;
public class Mail {
Session newSession = null;
MimeMultipart multiPart = new MimeMultipart();
MimeMessage mimeMessage = new MimeMessage(newSession);
public static void main(String[] args) throws MessagingException, IOException, AddressException {
Mail mail = new Mail();
mail.setupServerProperties();
mail.draftEmail();
mail.sendEmail();
}
private void setupServerProperties() {
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "587"); //was 547 changed // to 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
newSession = Session.getDefaultInstance(properties, null);
}
private MimeMessage draftEmail() throws AddressException, MessagingException, IOException {
String[] emailRecipients = {"abcd#gmail.com", "abcde#gmail.com"}; //who it is going to
String emailSubject = "Test Mail";
String emailBody = "Test body of email";
for(int i =0; i< emailRecipients.length; i++ ){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipients[i]));
System.out.println("This is i" + i);
}
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(emailBody, "html/text");
multiPart.addBodyPart(bodyPart);
mimeMessage.setContent(multiPart);
return mimeMessage;
}
private void sendEmail() throws MessagingException{
String fromUser = "yourPersonalEmail#gmail.com"; //sender
String fromUserPassword = "yourPassword"; //Password for senders email
String emailHost = "smtp.gmail.com";
Transport transport = newSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
System.out.println("Email Successfully sent");
}
}
I'm trying to setup a program which can automatically send e-mails. However, the first step doesn't even work for me and it gives this error:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at server.main(server.java:46)
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.base/java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
at java.base/java.net.PlainSocketImpl.connect(PlainSocketImpl.java:148)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
at java.base/java.net.Socket.connect(Socket.java:591)
at java.base/java.net.Socket.connect(Socket.java:540)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 7 more
This is the code:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class server {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "my other email properly written";
// Sender's email ID needs to be mentioned
String from = "my email properly written";
// Assuming you are sending email from localhost
String host = "127.0.0.1";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Does anyone have any idea why this happens and how to solve this? My e-mail is actually open etc. And because it's localhost I have no idea why it wouldn't work.
Access to a SMTP server would require the smtp host port and the security settings if applicable.
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "hostname") #
props.put("mail.smtp.port", "portnumber") #25
props.put("mail.smtp.starttls.enable", "boolean value true or false")
props.put("mail.smtp.auth", "boolean value true or false")
Usually a session need to be created (a Java mail session using the username and password and the properties), that is missing in the code above. For demonstration purpose,
Session session = javax.mail.Session.getInstance( props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("username", "password"); //username and password
}
});
package abc;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
public static void main(String[] args) {
// TODO Auto-generated method stub
String to="to#gmail.com";
String from="from#gmail.com";
final String username="from";
final String password="password";
Properties properties=new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", "587");
Session session=Session.getInstance(properties,
new javax.mail.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 Mail");
message.setText("Hey I wrote a java code to send mail. Thanks ");
Transport.send(message);
System.out.println("Sent Mail :)");
}
catch(MessagingException e){
e.printStackTrace();
}
}
}
I got the following errror whene i tried running the above code ::
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvHc
534-5.7.14 gCjfbim5WYCDTQee6sZlZ2d31nncueOizOcz9NieexN5nSlGr0c49lSZ43qc4RQPQvpWLH
534-5.7.14 qCUQUecjIR7qxdYJ5R_WgLxkzD9u4Ds3EEG7ceSMyTZg0dpSGJb-zl5C82YDTdLOYTX5Pl
534-5.7.14 tmEfWrmktFCdAxUjtDiPNruDLqhPSIZ9dd187tQjBtOw2X8zx7MUcysN9BRawwDmbXT6mJ
534-5.7.14 cLn_sJS5UBuqommn0uJK7W1tPZzU> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 qy7sm48619995pab.34 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at abc.SendMail.main(SendMail.java:36)
Gmail is not allowing this code. I even received a mail from gmail about suspicious logins and reviewed the devide from where i am running this code. What is the solution ?
It is AuthenticationFailedException, you should use the real username and password combination in order to get the program working and should give access to your program to sign-in to the gmail which explained in detail down below.
And also you should check this out to give access your program to send mail, the whole answer in the link given in the stack trace;
https://support.google.com/mail/answer/78754
What you have to do is (as explained in the link above);
Give access to your user;
https://accounts.google.com/DisplayUnlockCaptcha
Give access to less-secure sign-in;
https://www.google.com/settings/security/lesssecureapps
After then, If you try again to run your code with valid parameters, the test mail will be sent.
I'm currently working on a project that involves the creation of a .jar file. The following is to be achieved, I'm supposed to export/read the path of a friend's registry, once this is done I'm supposed to get the result back via email. The whole concept is in creating the jar file and once it's clicked I get the results through my email since I actually sent it through email.
(I hope this makes sense)
So first, I've combined the following code to actually read the registry and display the keys ( i got it from the popular post on stack overflow for read/write registries) so the reading process is working fine, now my problem is with the email code,
(I'm not quite sure who the original owner to this code is but full credit goes it him)
I'm trying to get the basic concept of this email code to work so that I can continue working on sending my jar file as an attachment and link it to my code in a way when a user clicks on the jar file, the registry results will be emailed back to me.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailCode {
public static void main(String[] args) throws Exception {
final String smtp_host = "smtp.gmail.com";
final String smtp_username = "user#gmail.com";
final String smtp_password = "password";
final String smtp_connection = "TLS"; // Use 'TLS' or 'SSL' connection
final String toEmail="tomail#hotmail.com";
final String fromEmail="**#gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username, smtp_password);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail, "Mr. Recipient"));
msg.setSubject("Welcome To JavaMail API");
msg.setText("JavaMail API Test - Sending email example through remote smtp server");
Transport.send(msg);
System.out.println("Email sent successfully...");
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
This is the error message I'm getting:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
The following code may help you to solve your problem, its working........
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", 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");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
You're setting smtp_host but you're never using it.
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
You're trying to connect to 'localhost' instead of gmail.com. That's becase you're not setting mail.smtp.host anywhere.
And why are you setting an SSL socket factory in the non-TLS case?
Please check your Antivirus/Malware.
If you are using corporate developer machine please contact your administrator to remove that access protection rule.
I had the same problem, my McAfee was blocking all the request.
Blocked by port blocking rule C:\PROGRAM FILES\JAVA\JDK1.8.0_74\BIN\JAVAW.EXE Anti-virus Standard Protection:Prevent mass mailing worms from sending mail 0:0:0:0:0:ffff:4a7d:7e6d:587
found this in Access protection log and requested my admin to remove that rule.
Try this might help you.
I need to send simple html-message with JavaMail. And when I tried to find some nice examples with explanations in the Internet, each next example made me more angry and angry.
All those silly examples contain copied and pasted Java code which differs only in comments and a nice disclaimer that first you should config your smtp and pop3 server.
I understand that nobody wants to make an advertise for some concrete products but configuring the server is imho the hardest part. So, can anyone give me some really useful information (without java code) about configuring concrete server (Kerio, for example, or any other one)?
What I have now is the next exception:
250 2.0.0 Reset state
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Relaying to <mymail#mycompany.com> denied (authentication required)
UPD. Simple reformulation of all previous text is: imagine that you have Windows, jdk, and nothing else. And you want to make java program and run it on your machine. And this program should send "Hello world!" to your gmail account. List your steps.
UPD2. Here is the code:
Properties props = new Properties ();
props.setProperty ("mail.transport.protocol", "smtp");
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty ("mail.user", "my_real_address_1#gmail.com");
props.setProperty ("mail.password", "password_from_email_above");
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 ("my_real_address_1#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO,
new InternetAddress ("my_real_address_2#gmail.com"));
transport.connect ();
transport.sendMessage (message,
message.getRecipients (Message.RecipientType.TO));
And exception is:
RSET
250 2.1.5 Flushed 3sm23455365fge.10
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 3sm23455365fge.10
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at com.teamdev.imgmail.MailSender.main(MailSender.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
If you're looking for a tutorial to configure an SMTP server, you shouldn't be looking for JavaMail. Simply look for a tutorial on your server of choice (Kerio, for example ... or Exim, SendMail, Apache James, Postfix) or ask on Serverfault. Any SMTP-compliant server will play nicely with JavaMail.
Alternatively, you may even use any "standard" mail provider's infrastructure. For example, I use a Google Apps account along with Google's SMTP infrastructure to send mail from our Java applications. Using a Gmail account is a good starting point anyway if you don't want to setup your own SMTP server in order to simply testdrive JavaMail.
As a last option, you might even lookup the MX Records for a domain and deliver your mails directly to the SMTP server of the recipient. There are some common gotchas to workaround tough.
As a last point, you'll have to look into how to avoid that your mails be filtered as spam - which is a huge topic itself. Here it helps to rely on standard providers that will deal with some of the issues you might encounter when hosting your own server.
Btw: Regarding the error message you posted: the SMTP server is denying relaying of messages. This is if your SMTP server (thinks that it) is running on example.com and you're sending as bob#example.net to alice#example.org, you're asking the SMTP server to act as a relay. This was common practice several years ago, until it was - you guessed it - abused by spammers. Since those days, postmasters are encouraged to deny relaying. You have two choices: authenticate before sending mail or send to accounts hosted at your server only (i.e. on example.com, e.g. alice#example.com).
Edit:
Here is some code to get you started with authenticationg (works with Gmail accounts but should do for your own server as well)
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.smtp.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.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("john.doe#gmail.com", "mypassword");
}
});
}
I can see part of your problem. It's adequately explained in the error message.
The SMTP server you are sending your mail to (i.e. one of the addresses you've configured in your JavaMail configuration) is refusing to forward mail to mymail#company.com. Looks like a configuration issue in your SMTP server. As sfussenegger indicated, it has nothing to do with javamail.
So you're not debugging on all fronts at the same time, it might be a good idea to try addressing your SMTP server from a known working SMTP client. Thunderbird would do fine, for example. If you can send mail through it from Thunderbird, there should be little problem from JavaMail.
Update:
The correct address for Google's SMTP server is: smtp.gmail.com . Is this the server you have configured in JavaMail? Can you show us the matching error message?
A working example combining the above answers, using activation-1.1.jar and mail-1.4.1.jar and the SMTP host is Gmail.
Replace user#gmail.com and user_pw in line return new PasswordAuthentication("user#gmail.com", "user_pw");
Also, you want to replace myRecipientAddress#gmail.com by the email address where you want to receive the email.
package com.test.sendEmail;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class sendEmailTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sendEmailTest emailer = new sendEmailTest();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail();
}
/**
* Send a single email.
*/
public void sendEmail(){
Session mailSession = createSmtpSession();
mailSession.setDebug (true);
try {
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject ("HTML mail with images");
message.setFrom (new InternetAddress ("myJavaEmailSender#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO, new InternetAddress ("myRecipientAddress#gmail.com"));
transport.connect ();
transport.sendMessage (message, message.getRecipients (Message.RecipientType.TO));
}
catch (MessagingException e) {
System.err.println("Cannot Send email");
e.printStackTrace();
}
}
private Session createSmtpSession() {
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");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user#gmail.com", "user_pw");
}
});
}
}
This should work:
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Emailer {
public static void main(String[] args) {
String hostname = args[0];
final String userName = args[1];
final String passWord = args[2];
String toEmail = args[3];
String fromEmail = args[4];
String subject = args[5];
String body = "";
// add rest of args as one body text for convenience
for (int i = 6; i < args.length; i++) {
body += args[i] + " ";
}
Properties props = System.getProperties();
props.put("mail.smtp.host", hostname);
Session session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, passWord);
}
});
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
System.out.println("Cannot send email " + e);
}
}
}
You need to put the JavaMail mail.jar on your classpath for the javax.mail dependencies.
I'm not sure if Google lets you send email like you want to. How about trying another email provider, like your ISP's?