4
votes

Here is my code for sending the mail

package com.markEffy.aggregator.util;
import com.sun.mail.util.MailSSLSocketFactory;

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;

 public class EmailAgent {

        private static final String SMTP_HOST_NAME = "smtp.zoho.com";
        private static final String SMTP_PORT = "465";
        private static final String emailFromAddress = "[email protected]";
        private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        private String emailMsgTxt;
        private String emailSubjectTxt;
        private String[] sendTo = {""};

        private int msgBodyType;

        public EmailAgent (String sendToAddr, int msgType) throws Exception {
            this.sendTo[0] = new String(sendToAddr);
            this.msgBodyType = msgType;
            }
        public EmailAgent (String sendToAddr, String emailMsgTxt, String emailSubjectTxt) throws Exception {
            this.sendTo[0] = new String(sendToAddr);
            this.emailMsgTxt = emailMsgTxt;
            this.emailSubjectTxt = emailSubjectTxt;
            }

        public EmailAgent(String[] recipients, int msgType) {
            // TODO Auto-generated constructor stub
            this.sendTo = new String[recipients.length];
            for(int i=0;i<recipients.length;i++){
                this.sendTo[i]=recipients[i];
            }
            this.msgBodyType=msgType;

        }

        public  void sendMail() throws Exception {
            //System.out.println("inside send mail");

            MailSSLSocketFactory sf = new MailSSLSocketFactory();

            //Check if valid arguments are passed
            if ((this.sendTo == null)) {
                System.out.println ("Invalid arguments!");
                return;
            }

            int msgType = this.msgBodyType; 
            new EmailAgent(sendTo, msgType).sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt,
                    emailFromAddress, sf);
            System.out.println("Sucessfully Sent mail to All Users");
        }

        public void sendSSLMessage(String recipients[], String subject,
                String message, String from , MailSSLSocketFactory sf) throws MessagingException {
            boolean debug = true;
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST_NAME);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");

            Session session = Session.getDefaultInstance(props,
                    new javax.mail.Authenticator() 
                     {
                         protected PasswordAuthentication                   

                      getPasswordAuthentication() {
                            return new   
                         PasswordAuthentication("[email protected]", "support@1234$");
                        }
                    });

            session.setDebug(debug);

            Message msg = new MimeMessage(session);
            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);

            // Setting the Subject and Content Type
            msg.setSubject(subject);
            msg.setContent(message, "text/plain");

            Transport.send(msg);
       }
}           

I have added mail.jar and activation.jar in the lib folder of tomcat.I am using eclipse with tomcat 7,jre 7 and struts2.The following console error came while sending mail through Java:

DEBUG: JavaMail version 1.5.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
     : 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,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
    DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.5.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG: Exception loading provider, THROW: 
java.lang.NoSuchMethodException: com.sun.mail.smtp.SMTPTransport.(javax.mail.Session, javax.mail.URLName)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getConstructor(Unknown Source)
    at javax.mail.Session.getService(Session.java:813)
    at javax.mail.Session.getTransport(Session.java:742)
    at javax.mail.Session.getTransport(Session.java:682)
    at javax.mail.Session.getTransport(Session.java:662)
    at javax.mail.Session.getTransport(Session.java:719)
    at javax.mail.Transport.send0(Transport.java:248)
    at javax.mail.Transport.send(Transport.java:124)
    at com.markEffy.aggregator.util.EmailAgent.sendSSLMessage(EmailAgent.java)
    at com.markEffy.aggregator.util.EmailAgent.sendMail(EmailAgent.java)
    at com.markEffy.aggregator.web.RetrievePasswordAction.sendPasswordToEmail(RetrievePasswordAction.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

2
Could you at a little bit more implementation and project setup for us. It is really difficult to see what's happening just out of this stacktrace.mle
I have added some more details. Can u please help?user3681970
Obviously there is a version mismatch of your com.sun.mail.smtp.SMTPTransport class. Can you say, which version of mail.jar you are using?mle
I am using javamail-1.4.7.user3681970
Ok, here it is javamail 1.5.2, working without problems... can you look through your classpath and verify that no other mail-implementations are present, so that we can eliminate version conflicts.mle

2 Answers

1
votes

So, I have just tested your code here, works perfectly with the following two mailing artifcats com.sun.mail:javax.mail:1.5.2 and javax.mail:javax.mail-api:1.5.2 Always keep the api-part and the implementation-part of your mailing artifacts in sync. So either change the mailapi-1.5.2 to mailapi-1.4.7 or update the javamail impl from 1.4.7 to 1.5.2.

2
votes

Read all of the answers in multiple versions of javamail jar causing NoSuchProviderException.

You can also modify your code to set the context class loader during send to fix this issue:

    Thread t =  Thread.currentThread();
    ClassLoader ccl = t.getContextClassLoader();
    t.setContextClassLoader(session.getClass().getClassLoader());
    try {
        Transport.send(msg);
    } finally {
        t.setContextClassLoader(ccl);
    }