网站首页 新闻首页 网页设计图形动画软件编程网站开发办公软件操作系统数据库网络技术认证考试范文资料黑客攻防 书籍教程 进入论坛

利用代理发邮件 javamail

http://www.diybl.com/ 2008-3-8  网络 点击:  [ 评论 ]
文章搜索:    【点击打包该文章】

 

        上个文章简单说了一下两种直连邮件服务器的发送邮件方法,但是实际环境中我们可能需要在此基础上加上代理,这篇文章专门解说一下如何利用代理发送邮件,之所以专门拿出来说是因为在摸索代理的时候有一个地方要特别注意(在我机器上确实发生了,或许您也可能遇到)

       代码如下 

 



package com.yourcompany.mail;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class example {

    
public static void main(String[] args) throws AddressException,
            MessagingException 
{
        Security.addProvider(
new com.sun.net.ssl.internal.ssl.Provider());
        
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        
// Get a Properties object
//        Properties props = new Properties();    方式一    
        Properties props = System.getProperties(); //方式二
        props.setProperty("proxySet""true");
        props.setProperty(
"socksProxyHost""172.16.128.86");   //socke5代理服务器地址
        props.setProperty(
"socksProxyPort""1089");

        props.setProperty(
"mail.smtp.host""smtp.sohu.com");
        props.put(
"mail.smtp.auth""true");
        
final String username = "xxxxx"// 用户名
        final String password = "xxxxx"// 密码

        Session newSession 
= Session.getInstance(props);
        MimeMessage message 
= new MimeMessage(newSession);
        InternetAddress from 
= new InternetAddress("xxx@sohu.com"); // 发件人邮箱
        message.setFrom(from);
        InternetAddress sto 
= new InternetAddress("xxxx@xxx.com"); // 收件人邮箱
        message.setRecipient(Message.RecipientType.TO, sto);
        message.setRecipient(Message.RecipientType.CC, sto);
        message.setRecipient(Message.RecipientType.BCC, sto);
        message.setSubject(
"hello");
        message.setSentDate(
new Date());
        BodyPart mdp 
= new MimeBodyPart();
        mdp.setContent(
"how are you""text/html;charset=gb2312");
        Multipart mm 
= new MimeMultipart();
        mm.addBodyPart(mdp);
        message.setContent(mm);
        Transport transport 
= newSession.getTransport("smtp");
        transport.connect(
"smtp.sohu.com", username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        System.out.println(
"Message sent.");
    }


}

 

         假如不利用代理发送邮件,那么在设置props的地方,方式一和二都可以,但是假如用代理发送邮件,那么在我本机测试的时候必须采用方式二。



文章整理:DIY部落 http://www.diybl.com (本站)   【点击打包该文章】
如果图片或页面不能正常显示请点击这里 站内搜索:   

文章评论

请您留言

 

最新新闻