Here, we are going to see how to send mail using JAVA MAIL API.
First, you need mail.jar in your project. If you have, copied it otherwise you can download.
Here are few notes, when you are going to create program for mail sending:
1) It is always better to create SESSION instance in your code.
2) Make sure you are using correct information about your SMTP host.
3) Sender and recipient’s mail-id must be valid and active.
Now, we will see examples:
1: The Properties class represents a persistent set of properties. So create an object of Properties and set all required parameters into this object:
2: Create Session instance to authenticate user:
3: Now, Create an object of java.mail.Message with created object of Session:
Now, set required parameters which are used in sending mail, to message object:
Now, Send Message:
If you are trying to send mail using gmail SMTP, first you need to disable security. You can find this option in your gmail setting or when you send mail, you will get one mail from gmail which will help you to disable security.
You can find below the code which sends mail using gmail SMTP:
There are few exception, which you get often:
- UnknownHostException : SMTP HOST
Ping to your SMTP host from command line. Make sure you get response (Success) because sometimes your firewall may block your connection.
Check your username and password. If this is correct, try to login using your browser and make sure given user information are correct.
- Could not connect to SMTP host
Check your SMTP host name and SMTP port, this is correct or not. Execute telnet command from your command prompt and check you are able to connect or not. Telnet command is:
C:\> telnet <SMTP HOST> <SMTP PORT>