Solved

java program to send emails

Posted on 2006-06-16
18
2,002 Views
Last Modified: 2013-11-24
Hello  all,

I want to write a java application that can just send emails to the client.

Do I have to consider what type of mail server does the sender's email belong to?
Do I have to consider what type of mail server (and hence what protocol that mail server uses) does the client's email belong to?

while writing this application.

I went through the documentation of java mail api. And it has all description @ the type of mail server etc.

Pl help.

Thanks
0
Comment
Question by:at999
  • 6
  • 4
  • 3
  • +2
18 Comments
 
LVL 10

Accepted Solution

by:
mukundha_expert earned 75 total points
ID: 16922279
0
 

Author Comment

by:at999
ID: 16922729
Thanks mukundh,

in those examples they have used SMTP based mail servers.

What if I want to use mail server like mail.yahoo.com  ?  for example -

String host = "mail.yahoo.com";
String from = "molly_t52@yahoo.com;
String to = "molly_t52@yahoo.com";



Also that code gave error, when I tried to send to my yahoo account.!!
Error is - javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
        com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for molly_t52@yahoo.com
     at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
        at javax.mail.Transport.send0(Transport.java:169)
        at javax.mail.Transport.send(Transport.java:98)
        at emailapplication.Main.main(Main.java:66)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1


'molly_t52@yahoo.com' is a valid address!!!
0
 

Author Comment

by:at999
ID: 16923889
Hello All,

I know I am disturbing u guys in the weekend,

but,

I am very confused
The scenario  is - I am trying to connect to send an email yahoo account( without logging into it i mean without providing username/password)  to any mail server account -

wat kind of issues may arise?

do i have to write seperate code for different kind of mail servers?

pl help

0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 16925205
the from Address and to address should be of type InternetAddress.

 InternetAddress from = new InternetAddress(from address);
          InternetAddress[] to = InternetAddress.parse(coma sepearted list of TO Address);

Also you have to validate urself ( like logging in ) first before sending a mail.
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 16925212
if you are able to configure your yahoo account with your local mail client like outlook, then this code will definitely work
0
 
LVL 8

Assisted Solution

by:kaliyugkaarjun
kaliyugkaarjun earned 75 total points
ID: 16925795
Hi at999,
Follow these instructions ..
You need to have Javasoft's JavaMail class files which can be downloaded from here http://www.javasoft.com/products/javamail/index.html

You will also need the JavaBeansTM Activation Framework extension or JAF (javax.activation). It is available at http://java.sun.com/beans/glasgow/jaf.html

-----------------------------------------------------------------------------
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.jcom.net");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    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[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[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(message, "text/plain");
    Transport.send(msg);
}
---------------------------------------------------------------

       

Sending Email From Your Application Using Java Mail

By Sudhir Ancha

Now a Day's informing the Clients about the successful updation of data or sending other automated information form your Java Programs, either from your Servlets or from your Applications has become a requirement, more than a feature. Here we show how to use the Java Mail API to send a Mail. To Test Program all you need to have is a SMTP address (Which your ISP Provides).

Before Using this Program, you need to have Javasoft's JavaMail class files which can be downloaded from here http://www.javasoft.com/products/javamail/index.html

You will also need the JavaBeansTM Activation Framework extension or JAF (javax.activation). It is available at http://java.sun.com/beans/glasgow/jaf.html.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.jcom.net");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    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[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[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(message, "text/plain");
    Transport.send(msg);
}


To Send a Email, from your Program, just call the above method, With the following parameters,

String to -- Email Address of the Recipient

String subject  -- Email Subject

String message -- Content or Body of the Message

String from -- Your (Senders) Email Address

smtp.jcom.net -- Replace this with your ISP's SMTP address.

That's it, you are all set to send a Email.

If your SMTP Server need you to do Authentication using Username and Password before Sending out mail, download the complete code from here :
http://www.javacommerce.com/destination65673/18274/SendMailUsingAuthentication.java
0
 
LVL 4

Assisted Solution

by:orhanbaba
orhanbaba earned 75 total points
ID: 16926597
you must use pop3 protocol to send mail if you are not using your own server
look at the sample code below and use a pop3 account such as gmail or your own.
http://www.javaworld.com/javaworld/jw-06-1999/jw-06-javamail-p2.html
0
 

Author Comment

by:at999
ID: 16930747
How can I find what protocol to use - POP3 or SMTP ?

Does it depend on the sender's email address or the recipient's email address?

KalyugkaArjun,

I tried to connect to mx4.mail.yahoo.com (sending from my yahoo account, to my own email address)
but I got error that 'Could not connect to SMTP host'
javax.mail.MessagingException:
java.net.ConnectException: Connection timed out: connect
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Expert Comment

by:orhanbaba
ID: 16930797
use gmail.
on your gmail account setting there is an option enable pop than use gmail smtp and pop server.
by default pop server uses 110 when you use gmail you have to use it like this
pop.gmail.com:460 (i am not sure about port number just gived an example)
0
 
LVL 4

Expert Comment

by:orhanbaba
ID: 16930800
yahoo, hotmail does not support pop3 for free accounts.
0
 

Author Comment

by:at999
ID: 16931715
orhanbaba?
this means SENDER's mail shud be GMAIL and not yahoo or hotmail? But receiver's mail can be of any type!!!

But, i can send yahoo to yahoo using  smtp - props.put("mail.smtp.host", host);


but i cannot send from an email server of the type 'IMAP'( e.g. xyz@us.gov etc). The mail server is configured on msexchange and i can access it through msexchange website. But when I try to send mail through java code,
I get error-

java.net.ConnectException: Connection refused: connect

 java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
        at javax.mail.Service.connect(Service.java:275)
        at javax.mail.Service.connect(Service.java:156)
        at javax.mail.Service.connect(Service.java:105)
        at javax.mail.Transport.send0(Transport.java:168)
        at javax.mail.Transport.send(Transport.java:98)
        at emailmanagement.Main.main(Main.java:73)
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
        at java.net.Socket.connect(Socket.java:461)
        at java.net.Socket.connect(Socket.java:411)
        at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
        ... 7 more
 */    


0
 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 75 total points
ID: 16934071
>> props.put("mail.smtp.host", host);

that is for the server from which you are sending, not to which you are sending.
0
 

Author Comment

by:at999
ID: 16934625
ya i can send from yahoo to yahoo by setting following two properties -

mail.smtp.host  = mx4.mail.yahoo.com
mail.smtp.auth = true

I have validator class etc. And yahoo to yahoo(or hotmail) works fine!!!

Now I am tryign to send FROM a Mail server of the type - Microsoft Exchange Server
So I am setting following two properties -
mail.imap.host = mail.myhost.com
mail.imap.auth  = true
I am settign values for IMAP Protocol. Is this method OK for Microsoft Exchange type of server???
But I am getting error message that 'Connection Refused'
Does it mean there is some firewall or some setting on mail server that is stopping this connection?

0
 

Author Comment

by:at999
ID: 16934730
How can I find what protocol to use?
SMTP,
POP3 or IMAP?

How can I find exact name of the mail server to set the 'mail.smtp.host' property (or similarly mail.imap.host property)

I checked by sending a simple email using msexchange web version ie. mail.myhost.com/exchange. I sent this sample mail from this website to my yahoo a/c . Once I recd that mail in yahoo, I opend 'Full Headers' To view

        X-Originating-IP:
        Authentication-Results:
        Message-ID:
        etc.

Is this a proper way to find the exact name of the mail server. Like yahoo to yahoo does not work if you set mail.smtp.host to value 'mail.yahoo.com' . You have to set that to 'mx4.mail.yahoo.com'
How can I find these exact values for the mail serverss? is there any technique?


 
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 16934766
>> But I am getting error message that 'Connection Refused'

Are you able to ping to mail.myhost.com? Maybe you should also try specifying the port number.
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 16939621
if you want to send a mail you should use SMTP.. i think IMAP and POP3 are for receiving mail.

Microsoft exchange server supports SMTP for sending mail
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now