`
LHacker
  • 浏览: 4517 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

java 发邮件

    博客分类:
  • java
阅读更多

介绍两种发邮件的方式,也是从网上得来的资料,收藏。

 

一,commons-email方式

     导入commons-email-1.1.jar包,代码如下:

 

 

public void sendMail() {   

        SimpleEmail email = new SimpleEmail();   

        email.setTLS(true);       

        email.setHostName("smtp.163.com");   

        email.setAuthentication("**@163.com", "密码****"); // 用户名和密码   

 

        try {   

            email.addTo("**@qq.com"); // 接收方   

            email.setFrom("**@163.com"); // 发送方   

            email.setSubject("Dylan's email"); // 标题   

            email.setCharset("GBK");   

            email.setMsg("hello,i am Dylan"); // 内容   

            email.send();   

 

        } catch (EmailException e) {   

            e.printStackTrace();   

        }   

    } 

 

 

二 spring方式

 

导入spring所需jar包,代码如下:

 

(1)配置emailsender

 

                <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

<property name="host" value="smtp.qq.com" />

<property name="port" value="25" />

<property name="username" value="**@qq.com" />

<property name="password" value="密码**" />

<property name="javaMailProperties">

<props>

<prop key="mail.smtp.auth">true</prop>

</props>

</property>

</bean>

 

(2)代码

public void sendMail() {   

 

               ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/application-root.xml");  

       JavaMailSender mailSender= (JavaMailSender) context.getBean("mailSender");  

       SimpleMailMessage mail = new SimpleMailMessage();  

       mail.setFrom("**@qq.com");  

       mail.setTo("**@163.com");  

       mail.setSubject(" 测试spring Mail");  

       mail.setText("hello,java");  

       mailSender.send(mail);  

}

 

方法都很简单。主要确保邮箱开启了SMTP服务

 

分享到:
评论
1 楼 shuye1 2012-08-01  
期待楼主继续发表高深技术

相关推荐

Global site tag (gtag.js) - Google Analytics