Announcement Announcement Module
Collapse
No announcement yet.
problem sending an email with javamail Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • #16
    Works!

    Originally posted by jrade View Post
    This does not work anymore. Once I get it working, I will post a solution. Most likely the port value has changed with gmail.

    This works, my apologies. Firewall was blocking all SMTP POP ports.

    Comment


    • #17
      Originally posted by ostewart View Post
      To send mail over an authenticated connection, you need to setup the Session with an Authenticator implementation. That's not provided by Spring out of the box, but you can easily wire in your own implementation. For gmail, you'd do something like this:
      Code:
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
      	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xsi:schemaLocation="http://www.springframework.org/schema/beans
      							http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
      
              <!-- our Authenticator implementation -->
      	<bean id="smtpAuthenticator"
      		class="forums.mailtest.SmtpAuthenticator">
      		<constructor-arg value="[email protected]" />
      		<constructor-arg value="password" />
      	</bean>
      
              <!-- now setup an authenticated session -->
      	<bean id="mailSession" class="javax.mail.Session"
      		factory-method="getInstance">
      		<constructor-arg>
      			<props>
      				<prop key="mail.smtp.auth">true</prop>
      				<prop key="mail.smtp.socketFactory.port">465</prop>
      				<prop key="mail.smtp.socketFactory.class">
      					javax.net.ssl.SSLSocketFactory
      				</prop>
      				<prop key="mail.smtp.socketFactory.fallback">
      					false
      				</prop>
      			</props>
      		</constructor-arg>
      		<constructor-arg ref="smtpAuthenticator" />
      	</bean>
      
              <!-- and configure the MailSender with the authenticated session -->
      	<bean id="mailSender"
      		class="org.springframework.mail.javamail.JavaMailSenderImpl">
      		<property name="host" value="smtp.gmail.com" />
      		<property name="session" ref="mailSession" />
      	</bean>
      
      	<!-- this is a template message that we can pre-load with default state -->
      	<bean id="templateMessage"
      		class="org.springframework.mail.SimpleMailMessage">
      		<property name="from" value="[email protected]" />
      		<property name="subject" value="Testing" />
      	</bean>
      
      	<bean id="mailTest" class="forums.mailtest.MailTest">
      		<constructor-arg ref="mailSender" />
      		<constructor-arg ref="templateMessage" />
      	</bean>
      </beans>
      You need your own Authenticator implementation, which could be something like this:
      Code:
      package forums.mailtest;
      
      import javax.mail.Authenticator;
      import javax.mail.PasswordAuthentication;
      
      public class SmtpAuthenticator extends Authenticator {
      	private String username;
      	private String password;
      	
      	public SmtpAuthenticator(String username, String password) {
      		super();
      		this.username = username;
      		this.password = password;
      	}
      
      	public PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication(username, password);
      	}
      }
      And here's the test class to send the actual message:
      Code:
      package forums.mailtest;
      
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      import org.springframework.mail.MailException;
      import org.springframework.mail.MailSender;
      import org.springframework.mail.SimpleMailMessage;
      
      public class MailTest {
      	private MailSender mailSender;
      	private SimpleMailMessage templateMessage;
      	public MailTest(MailSender mailSender, SimpleMailMessage templateMessage) {
      		super();
      		this.mailSender = mailSender;
      		this.templateMessage = templateMessage;
      	}
      	
      	public void sendMeMail() {
      		SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
      		msg.setTo("[email protected]");
      		msg.setText("This is a test.\nGo Spring!\n");
      		try {
      			this.mailSender.send(msg);
      		} catch (MailException e) {
      			System.err.println("Didn't work.");
      			e.printStackTrace();
      		}
      	}
      	
      	public static final void main(String[] args) {
      		ApplicationContext appCtx = new ClassPathXmlApplicationContext(new String[] {
      				"forums/mailtest/application-config.xml"
      		});
      		
      		MailTest tester = (MailTest) appCtx.getBean("mailTest");
      		tester.sendMeMail();
      	}
      }
      Note that you should google for the connection settings for whatever mail server you're trying to use to send mail. For gmail, they're here:
      http://mail.google.com/support/bin/a...y?answer=13287

      I think yahoo and gmail both want you to use authentication, and you may need to use a different port for each.


      please your code work but just with simplemessage , can you rewrite your code using mimemessage because I need to attach a file , and if possible make the authentification in the MailTest not defined in the application-config thaaaaaanks

      Comment


      • #18
        please help i did everything correctly in it i have both mail.jar and activaion.jar in the required java directory but still i'm getting this error

        23:32:40,890 ERROR org.springframework.osgi.context.support.OsgiBundl eXmlApplicationContext:307 - Post refresh error
        org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'mailSender' defined in URL [bundleentry://4.fwk32745991/META-INF/spring/spring.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/mail/MessagingException
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateBean(Abstrac tAutowireCapableBeanFactory.java:883)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:839)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:440)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory$1.run(AbstractAutowireC apableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 64)
        at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:222)
        at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:261 )
        at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:185)
        at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:164)
        at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:429)
        at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:728)
        at org.springframework.osgi.context.support.AbstractD elegatedExecutionApplicationContext.completeRefres h(AbstractDelegatedExecutionApplicationContext.jav a:288)
        at org.springframework.osgi.extender.internal.depende ncies.startup.DependencyWaiterApplicationContextEx ecutor$CompleteRefreshTask.run(DependencyWaiterApp licationContextExecutor.java:145)
        at java.lang.Thread.run(Unknown Source)
        Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Unk nown Source)
        at java.lang.Class.getConstructor0(Unknown Source)
        at java.lang.Class.getDeclaredConstructor(Unknown Source)
        at org.springframework.beans.factory.support.SimpleIn stantiationStrategy.instantiate(SimpleInstantiatio nStrategy.java:54)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateBean(Abstrac tAutowireCapableBeanFactory.java:877)
        ... 15 more
        Exception in thread "SpringOsgiExtenderThread-36" org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'mailSender' defined in URL [bundleentry://4.fwk32745991/META-INF/spring/spring.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/mail/MessagingException
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateBean(Abstrac tAutowireCapableBeanFactory.java:883)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:839)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:440)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory$1.run(AbstractAutowireC apableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 64)
        at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:222)
        at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:261 )
        at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:185)
        at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:164)
        at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:429)
        at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:728)
        at org.springframework.osgi.context.support.AbstractD elegatedExecutionApplicationContext.completeRefres h(AbstractDelegatedExecutionApplicationContext.jav a:288)
        at org.springframework.osgi.extender.internal.depende ncies.startup.DependencyWaiterApplicationContextEx ecutor$CompleteRefreshTask.run(DependencyWaiterApp licationContextExecutor.java:145)
        at java.lang.Thread.run(Unknown Source)
        Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Unk nown Source)
        at java.lang.Class.getConstructor0(Unknown Source)
        at java.lang.Class.getDeclaredConstructor(Unknown Source)
        at org.springframework.beans.factory.support.SimpleIn stantiationStrategy.instantiate(SimpleInstantiatio nStrategy.java:54)
        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateBean(Abstrac tAutowireCapableBeanFactory.java:877)
        ... 15 more


        urgent plzz help anyone

        Comment


        • #19
          Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException

          are the jars on your classpath?

          Comment


          • #20
            thanks for codes , i found via google , this is my first post . have nice days

            Comment


            • #21
              Good morning guys,

              I'm facing a problem with my e-mail sender. I have this conf:

              Code:
                      <bean id="mailSession" class="javax.mail.Session" factory-method="getInstance">
              		<constructor-arg>
              			<props>
              				<prop key="mail.smtp.auth">true</prop>
              				<prop key="mail.smtp.socketFactory.port">465</prop>
              				<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
              				<prop key="mail.smto.socketFactory.fallback">false</prop>
              			</props>			
              		</constructor-arg>
              		<constructor-arg ref="smtpAutentificador"/>
              	</bean>
              	
              	<bean id="mailSender"
              		class="org.springframework.mail.javamail.JavaMailSenderImpl">
              		<property name="host" value="smtp.gmail.com" />
              		<property name="session" ref="mailSession" />
              	</bean>
              	
              	
              	<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
              		<property name="from" value="[email protected]"/>
              		<property name="subject" value="Testing"/>
              	</bean>
              	
              	<bean id="email" class="com.utils.EmailServlet">
              		<constructor-arg ref="mailSender"/>
              		<constructor-arg ref="templateMessage"/>
              	</bean>
              
                      <bean id="smtpAutentificador" class="com.utils.SmtpAutentificador">
              		<constructor-arg value="[email protected]"/>
              		<constructor-arg value="myPassword"/>
              	</bean>
              
                      <bean id="emailServlet" class="com.utils.EmailServlet" >
              		<constructor-arg ref="mailSender" />
              		<constructor-arg ref="templateMessage" />
              	</bean>

              and the classes that I send the e-mails are just the same as posted here. When I run it in my local machine, everything works fine, but when I deploy it on my JBOSS and try to send an e-mail I get this error:

              Code:
              07:54:38,963 ERROR [[/web]] Exception while dispatching incoming RPC call
              com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.client.rpc.EnviarEmailServiceRpc.enviarEmail(com.model.Regra,com.model.Usuario,java.lang.String,
              com.model.Usuario,java.lang.String) throws com.exception.Exception' threw an unexpected exception: 
              java.lang.IllegalAccessError: tried to access method javax.mail.internet.MimeBodyPart.setText
              (Ljavax/mail/internet/MimePart;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V from class javax.mail.internet.MimeMessage
                      at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java: 378)
                      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:581)
                      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:544)
                      at org.gwtrpcspring.RemoteServiceDispatcher.invokeAndEncodeResponse(RemoteServiceDispatcher.java:80)
                      at org.gwtrpcspring.RemoteServiceDispatcher.processCall(RemoteServiceDispatcher.java:53)
                      at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:224)
                      at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
                      at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
                      at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
                      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                      at com.server.servlet.AuthFilter.doFilter(AuthFilter.java:35)
                      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                      at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
                      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
                      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
                      at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
                      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:524)
                      at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
                      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
                      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
                      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
                      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
               ...
              Caused by: java.lang.IllegalAccessError: tried to access method javax.mail.internet.MimeBodyPart.setText(Ljavax/mail/internet/MimePart;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V from class javax.mail.internet.MimeMessage
                      at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1520)
                      at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1504)
                      at org.springframework.mail.javamail.MimeMessageHelper.setPlainTextToMimePart(MimeMessageHelper.java:847)
                      at org.springframework.mail.javamail.MimeMessageHelper.setText(MimeMessageHelper.java:794)
                      at org.springframework.mail.javamail.MimeMessageHelper.setText(MimeMessageHelper.java:767)
                      at org.springframework.mail.javamail.MimeMailMessage.setText(MimeMailMessage.java:168)
                      at org.springframework.mail.SimpleMailMessage.copyTo(SimpleMailMessage.java:197)
                      at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:303)
                      at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
              ...
              I use javax.mail-1.4.1 but when I try to use javax.mail-1.4.4 the same error occurs.
              Do you guys have any idea what's going on?

              Thanks for your help.
              Last edited by Andre.almeida; Mar 9th, 2011, 08:13 AM.

              Comment

              Working...
              X