Click here to Skip to main content
Email Password   helpLost your password?

Overview

Quick Mail is a simple way to send mail using Java API in Windows and SUN/UNIX.

Things Required, Where to Get and How to Install

  1. activation.jar
  2. dnsjava.jar.
  3. mail.jar
  4. sendmail.jar

Above all, you can get it from the Sun site. But, you can get all the jar files from Java_Mail_demo.zip which attached with this article.

Brief Description

This article will help you to send mails using Java API. I have given the basic Java program. You can integrate this with any UI for easy access.

Source Code

I have given sample code to use it.

    MimeMessage mimemessage = new MimeMessage(session);
    // set FROM
    mimemessage.setFrom(new InternetAddress(mailfrom));
    // set DATE
    mimemessage.setSentDate(new java.util.Date());
    // set SUBJECT
    mimemessage.setSubject(subject);

    // set TO address
    try
    {
        mimemessage.setRecipients(javax.mail.Message.RecipientType.TO, mailto);
    }
    catch(Exception exception1)
    {
        System.out.println("\tError in setting recipients ......\t" + 
                exception1.getMessage());
    }

    // set message BODY
    MimeBodyPart mimebodypart = new MimeBodyPart();
    mimebodypart.setText(text);

    // attach message BODY
    MimeMultipart mimemultipart = new MimeMultipart();
    mimemultipart.addBodyPart(mimebodypart);

    // attach FILE
    mimebodypart = new MimeBodyPart();
    try
    {
        FileDataSource filedatasource = new FileDataSource(filename);
        mimebodypart.setDataHandler(new DataHandler(filedatasource));
    }
    catch(Exception exception3)
    {
        System.out.println("\tError in sending file not been able to attach ......\t" 
                        + exception3.getMessage());
    }
    mimebodypart.setFileName(filename); // set FILENAME
    mimemultipart.addBodyPart(mimebodypart);
    mimemessage.setContent(mimemultipart);

    //set CC MAIL and SEND the mail
    if(!mailto.equals(""))
    {
        // set CC MAIL
        if(!ccmailid.equals(""))
        mimemessage.setRecipients(javax.mail.Message.RecipientType.CC, ccmailid);
        try
        {
                        // send MAIL
        Transport.send(mimemessage);
        System.out.println("\tSent Successfully..........");
        strResult = "\tSent Successfully..........";
        }
        catch(Exception exception4)
        {
        System.out.println("\tError in sending Address Try........." + 
                exception4.getMessage());
        }
    }
                else
    {
        System.out.println("\tMail operation Failed..........\t");
        strResult = "\tMail operation Failed..........\t";
    }
}

Just try it. It is simple to use.

Happy programming!

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
QuestionDisplaying the read coneten using javamail in HTML format
Arivudai NAmbi
1:42 25 Feb '09  
I am reading mail content using javamail only. I may get mail from "HTML", "RTF" or "Plain text format.If i am getting mail in "RTF" format, i need to show that in RTF format.(Ex: if we have table in mail, should show same table structure with content). If i am getting mail from HTML format, i need to show that in "HTML" format(Ex: if i have any hyperlink, it should display as link. if i have any table, should show in table format.
Presently, If i am getting mail as HTML format, read mail showing in the applicationlike, "

testing for value

testing...."
I need to show in html format.

hel pme please Smile
AnswerRe: Displaying the read coneten using javamail in HTML format
Ashraf Mohamed
6:45 25 Feb '09  
Hi,

Check the content and use this appropriate
MimeMultipart content = new MimeMultipart("alternative");
MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();

text.setText( "Your text content" );
text.setHeader("MIME-Version" , "1.0" );
text.setHeader("Content-Type" , text.getContentType() );

html.setContent("Your html content", "text/html");
html.setHeader("MIME-Version" , "1.0" );
html.setHeader("Content-Type" , html.getContentType() );

content.addBodyPart(text);
content.addBodyPart(html);

message.setContent( content )
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" , content.getContentType() );
message.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");


Hope this helps,

- Mohashar

visit www.mohamedashraf.tk

GeneralQuery for using Java Mail
DivyaKamli
0:09 8 Feb '09  
i wanna ask abt what u actually need to do to send an Email using java code that u gave.
the code that is here i got an error in this line
org.xbill.DNS.Record arecord[] = (new Lookup(smtphost, (short)15)).run();
what is it.
like can we just easily send email just writing these lines in our app.
GeneralRe: Query for using Java Mail
Ashraf Mohamed
3:03 8 Feb '09  
If you would have given valid smtphost then it will not give any error. This is a simple program which gives some idea about java mail. This not meant for intermediate/higher level java programmars.

visit www.mohamedashraf.tk

QuestionLogger
sawanram
22:57 26 Jun '08  
When we create logger object.It is locked.If requrinment is to read lines of logger file and create new automaticaly how can we do
AnswerRe: Logger
Ashraf Mohamed
19:09 28 Jun '08  
I think you can read the stream. i.e., read the characters while creating a file.

visit www.mohamedashraf.tk

GeneralError in sending Address Try ... null
chris pang
22:13 20 Dec '07  
How to solve this problem ?
QuestionInitializaiton Block = Null & other errors [modified]
hanozt_007
6:18 22 Aug '07  
Hi,

I did as per instructions, i downloaded your test application
but i m getting this error: Initializaiton Block = Null.
It goes into the catch loop at
org.xbill.DNS.Record arecord[] = (new Lookup(smtphost, (short)15)).run();
// Store all SMTP hosts and their Priority
for(int j = 0; j < arecord.length; j++)
it is getting null at the length!!!!

Then i tried to modify the code, by removing the above FOR loop and made the adjustemnts, so that i have only one smtphost...i hardcoded the IP address(i have confirmed that this is indeed the correct ip address)
But now i am getting the error:
Error in sending Address Try.........Invalid Addresses;
nested exception is:class com.sun.mail.smtp.SMTPAddressFailedException: 554 Relay rejected for policy reasons.
This time it goes into catch at : Transport.send(mimemessage); I checked, it is when i use the "cc". If i comment the cc part, then it runs successfully

I am using:
Eclipse SDK
Version: 3.1.2
Build id: M20060118-1600
JDK1.5.0

Any help will be greatly appreciated!!!!


-- modified at 13:08 Wednesday 22nd August, 2007
GeneralConnectException
Sabros
5:28 14 Aug '07  
i follow all steps but in running i get this exception

Mailing Process Started ............
strPriority=[10];strHostName=[smtp3.google.com.]
strPriority=[10];strHostName=[smtp4.google.com.]
strPriority=[10];strHostName=[smtp1.google.com.]
strPriority=[10];strHostName=[smtp2.google.com.]
Error in sending Address Try.........Could not connect to SMTP host: smtp3.google.com., port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
Mailing Process Ended ............

GeneralRe: ConnectException
Ashraf Mohamed
17:30 15 Aug '07  
Seems smtp server connect problems..Try this to checkthe smtp connection
Hi,
your smtp server is not relaying to the gmail server...you can check this using these steps
Take cmd prompt
1. c:> telnet smtp_servername 25
2. helo
3. mail from: xxx@xx.com
4. rcpt to: xxx@gmail.com
5. data
test mail
.
Do the above steps one bye one
Hope this helps

Cheers,
Mohashar


visit www.mohamedashraf.tk

Generalsend mail to other servers
Rudraxi
21:55 7 Aug '07  
Hi.
Thanks for the great tutorial.
I have a problem, however. I code in java servlets using smtpClient class to send mails, but am unable to send mails to outside servers(eg. gmail.com). the mailing list software however can send mails to all hosts.
Please find time to answer this soon.
Thanks and regards


Rudraxi Parashar
GeneralRe: send mail to other servers
Ashraf Mohamed
17:29 15 Aug '07  
Hi,
your smtp server is not relaying to the gmail server...you can check this using these steps
Take cmd prompt
1. c:> telnet smtp_servername 25
2. helo
3. mail from: xxx@xx.com
4. rcpt to: xxx@gmail.com
5. data
test mail
.
Do the above steps one bye one
Hope this helps

Cheers,
Mohashar

visit www.mohamedashraf.tk

GeneralInitialization Block = Null
Gitanjali Dua
2:45 14 Jun '07  
Hello,
I m getting Initialization Block.......null exception while running program on eclipse version 3.2.......i read that there is suggestion of using weblogic.jar file....but i am working on tomcat. So, plz reply what should i have to do????????????????????

plz reply its very urgent.....


Gitanjali Dua
GeneralRe: Initialization Block = Null
Ashraf Mohamed
21:48 1 Jul '07  
It doesnot matter which web server you are using. It's a matter of mail api's are there in classpath. Pls check the required jars are in the classpath.

visit www.mohamedashraf.tk

GeneralInitialization Block : Null
binoyvp
20:14 13 Jun '07  
help please !!!!

Lghj
oojk;j

GeneralInitialization Block.......null
Thermax
10:00 13 Mar '07  
Hello,
I m getting Initialization Block.......null exception while running program on eclipse version 3.2.......i read that there is suggestion of using weblogic.jar file....
but from where should i get it????
plz reply its very urgent.....
GeneralRe: Initialization Block.......null
Mohamed Ashraf
22:41 13 Mar '07  
Hi,

This is due to reference problem. You don't have appropriate jars then put weblogic.jar in the classpath and try it.

If you have weblogic you can get it from lib folder.

Rgs,
Ashraf Mohamed

visit www.mohamedashraf.tk

Generalinvalid address(urgent)
20:40 3 Mar '07  
here am getting these exception when am running the sendmail.java
Invalid address
i checked out classpath for jar files everything s correct

am using 1st smtp server downloaded frm web
i dont know y it is not working very urgent


plzzzzzzzzz reply me

GeneralRe: invalid address(urgent)
Mohamed Ashraf
4:07 4 Mar '07  
Hi,

Have you checked the smtp host name using telnet? Please check the smtp hostname is exist using following command

telnet smtpservername portnumber

If you still facing this problem send me the exception.

Hope ths helps.

Rgs
Mohashar

visit www.mohamedashraf.tk

GeneralRe: invalid address(urgent)
191832Sanjay
23:36 29 Jul '08  
Hi,

I have implemented the same logic into my test program. Its working fine for the correct email addresses, but if I put email address as abc@xyz.com, then also its sending. though no reciept msg is coming even then no exception is there.
GeneralRe: invalid address(urgent)
Ashraf Mohamed
19:18 30 Jul '08  
Unless until you handle the bounce using pop3 it will not be showing any receipt of the message.

SMTP is not a point to point type protocol.It simply delivers it and bounced message must be captured by pop mechanisms.

Hope this helps...

visit www.mohamedashraf.tk

QuestionProblem with Text
toriton
1:11 11 Jan '07  
Sending the mail i can set many attachments but the text of the mail is not displayed.

i mean the text like:

Subject: dinner

text:
where we meet?

if i add an attachment to the mail "where we meet" is not displayed.
but i f i don't attach nothing the text is showed.
AnswerRe: Problem with Text
Mohamed Ashraf
1:58 11 Jan '07  
You meant to say, if you add an attachment you are not able to see the body right. Please check the attachment part overwrite the body content.

visit www.mohamedashraf.tk

GeneralRe: Problem with Text
toriton
5:47 11 Jan '07  
is how you told Smile .. i was setting the body after all Attachment..
thanks for quick reply

GeneralIOException
LEELAPRASADMALLIPUDI
2:37 12 Dec '06  
hi,

I got the following error if i run my code.

javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: No content.

please help me.


Last Updated 14 Jun 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010