Incredible Today

Sending mail using JavaMail APIs

Posted on: April 8, 2007

This post has been moved to: http://www.pakzilla.com/2007/04/08/sending-mail-using-javamail-apis/

12 Responses to "Sending mail using JavaMail APIs"

Hi All. In case you want to do the reverse and retrieve mail from a POP3 account using JavaMail, I put together an axample at:
http://timarcher.com/?q=node/52

Hopefully it helps you all!

I also have a writeup that presents my EmailDelivery class (and example of how to use it) which I wrote to help me easily send emails from my Java applications using JavaMail. It supports relaying through SMTP servers that require authentication and has convenience methods for easily adding file attachments.

Check it out at:
http://timarcher.com/?q=node/53

Absolutely fine and working good. But the given is the code for sending emails. But can you provide us the code for getting the attachment name in case if the mail is bounced back.

TONS OF THANKS IN ADVANCE

Thanks Siva;

The thing you are telling to me is new to me, if I come up with this scenerio I will deffinately share with you. take care.

thats great!

just 10 minutes earlier i was assigned a task to know and configure java-mail.
i used your post, and done it in less than 10 mins.

thank you so much.

DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:

this is wat i m getting
can you help me out….

hi,
i dont know exactly what code you are composing. my code is as follow, plz check, it might help you.

public class JavaMail {
String
from_email = “asifsh7@gmail.com”,
password = “mypassword”,
host = “smtp.gmail.com”,
port = “465”;

Properties props = new Properties();

public JavaMail(){
props.put( “mail.smtp.user”, from_email );
props.put( “mail.smtp.host”, host );
props.put( “mail.smtp.port”, port );
props.put( “mail.smtp.starttls,enable”, “true” );
props.put( “mail.smtp.auth” , “true” );
props.put( “mail.smtp.socketFactory.class” ,”javax.net.ssl.SSLSocketFactory” );
props.put( “mail.smtp.socketFactory.fallback” , “false” );
}

public void sendEmail(String m_to, String m_subject, String m_text){
SecurityManager security = System.getSecurityManager();

try{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);

session.setDebug(true);
MimeMessage msg = new MimeMessage (session);
msg.setText(m_text);
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(from_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
}catch(Exception exp){
exp.printStackTrace();
}
}

private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(from_email, password);
}
}

public static void main( String arg[] ) {
JavaMail mail = new JavaMail();
mail.sendEmail(“asifshahzad@seantechsoft.com”, “subject here”, “msg body here ….”);
}
}

shriram!
check ur password. if still problem … paste your code here … and let me see.

shriram;

Initially I also got some relevant problem like you have. That I was unable to connect with SMTP server. I found my AntiVirus stopping my connection with it. You can check you Antivirus settings for this.

Check your code again by commenting props.put( “mail.smtp.port”, port ); I think it will/should use default port 25. Not full sure but give it a try and share your findings.

hi All.. i am getting the same exception as mentioned by shriram..
the solution proposed by tahir..//commenting the props.put( “mail.smtp.port”, port ); is taking the default port as 25.. but it is gining me the same exception.. the complete stack trace is as follows..

DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.5.0_03\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.5.0_03\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false
Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: 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:297)
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 GoogleTest.sendSSLMessage(GoogleTest.java:70)
at GoogleTest.main(GoogleTest.java:27)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
… 8 more

Please help!!!!!!!

Hi all,
Thanx a ton for the load of information.
I was wondering if it is possible to go through the content of an email without actually having to open the message and then retrieve certain info out of them (eg. embedded URLs).
If so, can someone please help me out with the code for the same.
Thanks in advance,

Hi Kapil,
Yes it is possible. What you have to do is:
1. Get the Inbox Folder

store = session.getStore( mailProps.getProperty( “MAIL_PROVIDER” ) );
store.connect( “mail.gmail.com”, “login”, “password” ) ;
inbox = store.getFolder( “INBOX” ) ;
inbox.open( Folder.READ_ONLY ) ;

2. Get Messages fron InBox
Message[] messages = null ;
messages = inbox.getMessages() ;

3. Iterate through each Message in messages array, read the Message Content section
for ( int i = 0; i < messages.length; i++ )
{
if (messages[i].getContentType().equals(“text/plain”))
{
String content = (String)messages[i].getContent();
// HERE APPY SOME STRING MATCHING PATTERN TO MATCH THE URL YOU ARE LOOKIN FOR INSIDE MAIL BODY, WHERE YOU FIND THE MATCH, … READ THAT URL …
}

if( messages[i].getContent() instanceof Multipart )
{ // ITS MEAN YOUR MESSAGE IS MULTIPART, WHICH SHOWS IT HAS SOME ATTACHMENTS ALSO, SO YOU NEED TO WRITE LOGIC TO PARSE MULTIPART MESSAGE.
}
}

I hope you get the idea, and will extend the above code to write parser for multipart messages. Then you will be ready to parse both messages body/content (plain messages, attachment message), and identify the embedded URLs inside them.

Regards!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog Moved to Pakzilla.com

I have moved my blog to my own domain www.Pakzilla.com. I will disable posting comments and going to link all posts to my new blog. For now I will make all updates and reply to your comments there. Please also update your RSS to this feed. http://feeds2.feedburner.com/pakzilla Thank you very much.


AddThis Social Bookmark Button

Networking

Blogosphere

Blog Stats

  • 93,379 hits

My Twitter updates

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Pages

April 2007
M T W T F S S
    Jul »
 1
2345678
9101112131415
16171819202122
23242526272829
30  
%d bloggers like this: