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

java 匿名Email (源码)

    博客分类:
  • java
阅读更多
 

/*
 * org.gsoft.mail.server.EmsFrame.java
 * Copyright  All rights reserved.
 */
package org.gsoft.mail.server;


import javax.swing.*;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.Attributes;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import java.awt.event.*;
import java.util.List;
import java.io.File;
import java.util.LinkedList;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Message;
import javax.mail.internet.MimeMultipart;
import javax.mail.BodyPart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;
import javax.mail.internet.MimeUtility;
import javax.mail.Multipart;
import java.util.Date;
import javax.mail.Transport;


/**
 * 
 * @author zealvampire
 * @version 1.0
 */
public class EmsFrame extends JFrame
{
    /** serialVersionUID */
    private static final long serialVersionUID = 5817303146163930933L;
    
    JLabel senderLabel = new JLabel();
    JTextField senderField = new JTextField();
    JLabel senderPromptLadbel = new JLabel();
    JLabel receiverLabel = new JLabel();
    JTextField receiverField = new JTextField();
    JLabel mailHeadLabel = new JLabel();
    JTextField mailHeadField = new JTextField();
    JList affixList = new JList();
    JLabel affixLabel = new JLabel();
    JButton addButton = new JButton();
    JButton delButton = new JButton();
    JScrollPane jScrollPane1 = new JScrollPane();
    JScrollPane jScrollPane2 = new JScrollPane();
    JButton sendButton = new JButton();
    JLabel contentLabel = new JLabel();
    JEditorPane contentPane = new JEditorPane();
    JButton resetButton = new JButton();
    
    javax.swing.JProgressBar bar = new javax.swing.JProgressBar();

    //附件列表
    private List affixFileList = null;

    public EmsFrame()
    {
        try
        {
            jbInit();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception
    {
        UIManager.setLookAndFeel(
            "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        EmsFrame emsFrame = new EmsFrame();
    }

    private void jbInit() throws Exception
    {
        Font standardFont = new Font("Dialog", 0, 14);
        senderLabel.setFont(standardFont);
        senderLabel.setBorder(null);
        senderLabel.setText("发信人:");
        senderLabel.setBounds(new Rectangle(32, 34, 56, 34));
        this.getContentPane().setLayout(null);
        this.setSize(600, 450);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("EMS 特快专递.");
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation( (int) (screen.getWidth() - 600) / 2,
                         (int) (screen.getHeight() - 450) / 2);

        senderField.setFont(standardFont);
        senderField.setText("anyname@21cn.com");
        senderField.setBounds(new Rectangle(92, 34, 249, 32));
        senderPromptLadbel.setFont(standardFont);
        senderPromptLadbel.setOpaque(false);
        senderPromptLadbel.setText("(支持匿名邮件发送)");
        senderPromptLadbel.setBounds(new Rectangle(366, 58, 135, 29));

        receiverLabel.setFont(standardFont);
        receiverLabel.setText("收件人:");
        receiverLabel.setBounds(new Rectangle(31, 78, 54, 37));
        receiverField.setFont(standardFont);
        receiverField.setText("receiver@21cn.com");
        receiverField.setBounds(new Rectangle(93, 79, 249, 32));

        mailHeadLabel.setFont(standardFont);
        mailHeadLabel.setText("邮件主题:");
        mailHeadLabel.setBounds(new Rectangle(31, 121, 76, 34));
        mailHeadField.setFont(standardFont);
        mailHeadField.setText("测试ems邮件");
        mailHeadField.setBounds(new Rectangle(93, 123, 344, 34));

        affixLabel.setFont(standardFont);
        affixLabel.setText("附件:");
        affixLabel.setBounds(new Rectangle(32, 171, 43, 32));
        addButton.setBounds(new Rectangle(472, 175, 74, 22));
        addButton.setText("添加");
        addButton.addMouseListener(new EmsFrame_addButton_mouseAdapter(this));
        delButton.setBounds(new Rectangle(472, 202, 75, 22));
        delButton.setText("删除");
        delButton.setEnabled(false);
        delButton.addMouseListener(new EmsFrame_delButton_mouseAdapter(this));

        jScrollPane1.setBounds(new Rectangle(93, 172, 342, 54));
        jScrollPane2.setBounds(new Rectangle(92, 237, 343, 161));
        sendButton.setBounds(new Rectangle(472, 279, 74, 25));
        sendButton.setText("发送");
        sendButton.addMouseListener(new EmsFrame_sendButton_mouseAdapter(this));
        contentLabel.setFont(standardFont);
        contentLabel.setText("内容:");
        contentLabel.setBounds(new Rectangle(30, 292, 55, 31));
        contentPane.setFont(standardFont);
        resetButton.setBounds(new Rectangle(472, 311, 74, 24));
        resetButton.setText("重置");
        
        bar.setIndeterminate(true);
        bar.setBounds(50, 400, 500, 12);
        bar.setString("发送中,请稍等..");
        bar.setStringPainted(true);
        bar.setVisible(false);

        this.getContentPane().add(senderLabel, null);
        this.getContentPane().add(senderField, null);
        this.getContentPane().add(receiverLabel, null);
        this.getContentPane().add(receiverField, null);
        this.getContentPane().add(mailHeadLabel, null);
        this.getContentPane().add(jScrollPane1, null);
        jScrollPane1.getViewport().add(affixList, null);
        this.getContentPane().add(mailHeadField, null);
        this.getContentPane().add(delButton, null);
        this.getContentPane().add(affixLabel, null);
        this.getContentPane().add(contentLabel, null);
        this.getContentPane().add(resetButton, null);
        this.getContentPane().add(jScrollPane2, null);
        jScrollPane2.getViewport().add(contentPane, null);
        this.getContentPane().add(senderPromptLadbel, null);
        this.getContentPane().add(addButton, null);
        this.getContentPane().add(sendButton, null);
        
        this.getContentPane().add(bar, null);

        this.setVisible(true);
    }

    /** *//**
     * 处理添加附件消息.
     * @param e 添加按钮消息
     */
    void addButton_mouseClicked(MouseEvent e)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("按住ctrl可选择多个附件:");
        chooser.setMultiSelectionEnabled(true);
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File[] files = chooser.getSelectedFiles();
            if (files != null)
            {
                if (affixFileList == null)
                    affixFileList = new LinkedList();
                for (int i = 0; i < files.length; ++i)
                    affixFileList.add(files[i].getAbsolutePath());
                affixList.setListData(affixFileList.toArray()); //待定.
                delButton.setEnabled(true);
            }
        }
    }

    /** *//**
     * 处理删除附件动作
     * @param e 删除按钮消息
     */
    void delButton_mouseClicked(MouseEvent e)
    {
        int[] indexes = affixList.getSelectedIndices();
        if (indexes == null || indexes.length <= 0)
        {
            showErrorDialog("删除附件出错!", "请首先选择需要删除的附件!");
            return;
        }

        for (int i = 0; i < indexes.length; ++i)
            affixFileList.set(indexes[i], null);
        for (int i = 0; i < affixFileList.size(); ++i)
        {
            if (affixFileList.get(i) == null)
            {
                affixFileList.remove(i);
                --i;
            }
        }

        affixList.setListData(affixFileList.toArray());
        if (affixFileList.size() <= 0)
            delButton.setEnabled(false);
    }

    private void showErrorDialog(String title, String errorMesg)
    {
        JOptionPane.showMessageDialog(this, errorMesg, title,
                                      JOptionPane.ERROR_MESSAGE);
    }

    /** *//**
     * 处理发送邮件
     * @param e 发送按钮消息
     */
    void sendButton_mouseClicked(MouseEvent e)
    {
//        //暂时默认所有参数合法.
//        MailMessage mesg = new MailMessage(senderField.getText().trim(),
//                                           receiverField.getText().trim(),
//                                           mailHeadField.getText().trim(),
//                                           contentPane.getText().trim());
//        try
//        {
//            sendMail(mesg);
//            if (affixFileList != null)
//            {
//                affixFileList.clear();
//                affixList.setListData(affixFileList.toArray());
//            }
//        }
//        catch (Exception ex)
//        {
//            showErrorDialog("发送邮件失败:", ex.toString());
//            return;
//        }
//
//        JOptionPane.showMessageDialog(this, "邮件发送成功!");
        SendThread thread = new SendThread(this);
        thread.start();


    }
    
    private class SendThread extends Thread {
        private EmsFrame frame = null;
        
        public SendThread (EmsFrame pFrame) {
            this.frame = pFrame;
        }
        public void run() {
            
            MailMessage mesg = new MailMessage(this.frame.senderField.getText().trim(),
                                               this.frame.receiverField.getText().trim(),
                                               this.frame.mailHeadField.getText().trim(),
                                               this.frame.contentPane.getText().trim());
            this.frame.bar.setVisible(true);
            try
            {
                this.frame.sendMail(mesg);
                if (affixFileList != null)
                {
                    affixFileList.clear();
                    affixList.setListData(affixFileList.toArray());
                }
                this.frame.bar.setVisible(false);
                JOptionPane.showMessageDialog(null, "邮件发送成功!");
            }
            catch (Exception ex)
            {
                this.frame.bar.setVisible(false);
                showErrorDialog("发送邮件失败:", ex.toString());
                return;
            }

        }
    }
    

    private void sendMail(MailMessage mesg) throws Exception
    {
        // DNS服务器,如果需要的话手工设置一下。
        String dns = "dns://";
       
       //得到接受方的服务器域名
       String domain = mesg.getTo().substring(mesg.getTo().indexOf('@') + 1);
       Hashtable env = new Hashtable();
       env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
       env.put(Context.PROVIDER_URL, dns);
       DirContext ctx = new InitialDirContext(env);
       Attributes attrs = ctx.getAttributes(domain, new String[] {"MX"});
       if (attrs == null || attrs.size() <= 0) {
           throw new java.lang.IllegalStateException("错误:你的DNS服务器没有相应的MX记录!");
       }
       NamingEnumeration servers = attrs.getAll();
       // 列出所有邮件服务器:
       String smtpHost = null;
       boolean isSend = false;
       StringBuffer buf = new StringBuffer();
       while (servers.hasMore())
       {
           Attribute hosts = (Attribute) servers.next();
           for (int i = 0; i < hosts.size(); ++i)
           {
               smtpHost = (String) hosts.get(i);
               smtpHost = smtpHost.substring(smtpHost.lastIndexOf(' ') + 1);
               try {
                   sendEms(smtpHost, mesg);
                   isSend = true;
                   return;
               } catch (Exception e) {
                   e.printStackTrace();
                   buf.append(e.toString()).append("\r\n");
                   continue;
               }
           }
       }
       if (!isSend) {
           throw new java.lang.IllegalStateException("错误:发送失败," + buf.toString());
       }
       
    }

    /**
     * 特快转递邮件发送
     * @param smtpHost 对方smtp服务器域名
     * @param mesg 发送方信息封装
     * @throws Exception
     */
    private void sendEms(String smtpHost, MailMessage mesg) throws Exception
    {

        Properties p = System.getProperties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", "25");
        p.put("mail.smtp.auth", "f");
        Session session = Session.getInstance(p, null);
        session.setDebug(true);

        Message  mimeMessage = new MimeMessage (session);
        mimeMessage.setFrom(new InternetAddress(mesg.getFrom()));//可发匿名信
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mesg.getTo()));
        mimeMessage.setSubject(mesg.getTitle());
        mimeMessage.setHeader("X-Mailer", "JavaMail");
        mimeMessage.setSentDate(new Date());        

        Multipart mimeMultipart = new MimeMultipart();

        //内容部分.
        BodyPart contentBodyPart = new MimeBodyPart();
        contentBodyPart.setContent(mesg.getContent(), "text/html;charset=GB2312");
        mimeMultipart.addBodyPart(contentBodyPart);

        //附件部分
        if (affixFileList != null && affixFileList.size() > 0)
        {
            BodyPart fileBodyPart = null;
            String filePath = null;
            FileDataSource fileDataSource = null;
            for (int i = 0; i < affixFileList.size(); ++i)
            {
                filePath = (String) affixFileList.get(i);
                fileBodyPart = new MimeBodyPart();
                fileDataSource = new FileDataSource(filePath);
                fileBodyPart.setDataHandler(new DataHandler(fileDataSource));
                fileBodyPart.setFileName(MimeUtility.encodeWord(fileDataSource.
                    getName(), "GB2312", null));
                mimeMultipart.addBodyPart(fileBodyPart);
            }
        }

        mimeMessage.setContent(mimeMultipart);
        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();

        //发送
        Transport.send(mimeMessage);
    }

 

}

class EmsFrame_addButton_mouseAdapter extends java.awt.event.MouseAdapter
{
    EmsFrame adaptee;

    EmsFrame_addButton_mouseAdapter(EmsFrame adaptee)
    {
        this.adaptee = adaptee;
    }
    public void mouseClicked(MouseEvent e)
    {
        adaptee.addButton_mouseClicked(e);
    }
}

class EmsFrame_delButton_mouseAdapter extends java.awt.event.MouseAdapter
{
    EmsFrame adaptee;

    EmsFrame_delButton_mouseAdapter(EmsFrame adaptee)
    {
        this.adaptee = adaptee;
    }
    public void mouseClicked(MouseEvent e)
    {
        adaptee.delButton_mouseClicked(e);
    }
}

class EmsFrame_sendButton_mouseAdapter extends java.awt.event.MouseAdapter
{
    EmsFrame adaptee;

    EmsFrame_sendButton_mouseAdapter(EmsFrame adaptee)
    {
        this.adaptee = adaptee;
    }
    public void mouseClicked(MouseEvent e)
    {
        adaptee.sendButton_mouseClicked(e);
    }
}

class MailMessage
{
    private String from = null;
    private String to   = null;
    private String title   = null;
    private String content = null;

    public MailMessage (String from, String to, String title, String content)
    {
        this.from = from;
        this.to = to;
        this.title = title;
        this.content = content;
    }

    public String getFrom()
    {
        return this.from;
    }

    public String getTo()
    {
        return this.to;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getContent()
    {
        return this.content;
    }

}

分享到:
评论

相关推荐

    JavaEmail完整版

    JavaEmail完整版是一个Java开发的电子邮件发送库,它允许开发者通过编程的方式发送电子邮件。这个源码包包含了完整的实现,提供了详细的示例和配置文件,使得开发者可以快速理解和使用。下面我们将详细探讨JavaEmail...

    Java多商户外贸版正式发布!多语言、国际支付、短信登录等CRMEB-JAVA-ET-V1.0.0(0620)(完整包)

    部署后对应操作的端有:平台端,商户端,H5商城,PC商城 1、后台框架 SpringBoot 简单易用 JDK 1.8 市场保有量最大 ...备注:本源码为官方正版源码,非破解版,仅供下载研究学习,商业使用请联系购买授权!

    CRMEB Java【外贸版】多商户系统+PC前端模板,多国语言、国际支付、短信登录等

    ava多商户外贸版正式发布!多语言、国际支付、短信登录等,快来 部署后对应操作的端有:平台端,商户端,H5商城,PC商城 1、后台框架 ...原版源码,未做任何修改处理,仅供研究学习,授权请支持正版!

    java代码发送email

    JavaMail API是一个开放源码的库,它提供了一系列的接口和类,使得开发者能够方便地处理邮件发送、接收等操作。 首先,发送电子邮件涉及的主要类有`Session`、`Message`、`Transport`和`MimeMessage`。`Session`是...

    实现匿名邮件发送

    如果你是在源码级别实现,可以使用各种编程语言的网络库,例如Python的smtplib和email库,或者是.NET框架下的System.Net.Mail。这些库允许你直接与SMTP服务器交互,构建并发送邮件。在构建邮件时,你需要设置发件人...

    Android-YAVI-基于lambda的Java类型安全验证

    Lambda表达式是Java 8引入的一个重要特性,它允许开发者以更简洁的方式编写匿名函数。在YAVI中,我们可以用lambda表达式来创建验证规则,例如检查字符串是否为空、整数是否大于零等。这样的写法使得验证逻辑清晰...

    Linux软件安装并实现部署项目

    在Linux上,可以使用包管理器安装MySQL Server,并通过`mysql_secure_installation`脚本初始化设置,包括设置root密码、删除匿名用户和测试数据库。别忘了创建项目所需的数据库和用户,并分配相应的权限。 Maven是...

    Android开发案例驱动教程 配套代码

    4.3.3 匿名内部类事件处理模型 51 4.4 Activity中的常用事件 53 4.4.1 触摸事件 53 4.4.2 键盘事件 55 4.5 菜单 57 4.5.1 文本菜单 57 4.5.2 图片文本菜单 59 本章小结 60 第5章 UI基础控件 61 5.1 按钮 61...

    spring Boot 集成swagger2全过程(代码包含集成Spring Security+ JWT)

    创建一个`WebSecurityConfig`类,配置允许匿名访问`/v2/api-docs`和`/swagger-ui.html`: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @...

    PHP基础教程 是一个比较有价值的PHP新手教程!

    据我所知,JSP基于Java,因此Java程序员可以轻松开始编码。ASP只是一个一般的引擎,具有支持多种语言的能力,不过默认的并且是最常用的还是VBScript。 mod_perl与Perl一样强大,只是更快一些。 二、PHP入门 PHP...

Global site tag (gtag.js) - Google Analytics