介绍:
SendMail是一款简便的163邮箱发件工具
利用了163的SMTP接口来发送邮件
版本号:SendMail v1.0
在编写发送邮件工具之前,还需要安装 JavaMail API 和Java Activation Framework (JAF) 两个jar包
下载链接:https://files.cnblogs.com/files/wh4am1/mailAPI.zip
整体程序的逻辑构造如下
思路出来后,我们就利用eclipse IDE集成开发工具定制一个程序大概的框架
关于eclipse的可视化编程,可以使用windowbuilder插件:https://blog.****.net/jason0539/article/details/21219043
首先做出一个登陆窗口,是由一个账号编辑框、一个密码编辑框和按钮组成
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.util.Properties;
import javax.mail.*;
import com.sun.mail.util.MailSSLSocketFactory;
import java.awt.Button;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.security.GeneralSecurityException;
import javax.swing.JLabel; public class mailSend extends JFrame { /**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField Username;
private JPasswordField Password;
private JLabel lblUsername;
private JLabel lblPassword;
private JLabel lblwham; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mailSend frame = new mailSend();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} class SimpleAuthenticator extends Authenticator {
private String user;
private String pwd;
public SimpleAuthenticator(String user, String pwd) {
this.user = user;
this.pwd = pwd;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pwd);
}
} /**
* Create the frame.
* @throws GeneralSecurityException
* @throws NoSuchProviderException
*/
public mailSend() throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.163.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true"); //开启SSL加密,不然会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf); setTitle("SendMila v1.0");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 415, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null); Button button = new Button("\u767B\u5F55");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Session session = Session.getInstance(prop,new SimpleAuthenticator(Username.getText(),new String(Password.getPassword())));//测试邮件登陆
Transport ts = session.getTransport();
ts.connect();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SendText frame = new SendText(session,Username.getText());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}catch(AuthenticationFailedException e1) {
JOptionPane.showMessageDialog(null, "用户名或者密码错误!", "ERROR", JOptionPane.ERROR_MESSAGE);
} catch (NoSuchProviderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
});
button.setBounds(169, 156, 87, 25);
contentPane.add(button); Username = new JTextField();
Username.setBounds(131, 41, 212, 25);
contentPane.add(Username);
Username.setColumns(10); Password = new JPasswordField();
Password.setBounds(131, 96, 212, 24);
contentPane.add(Password); lblUsername = new JLabel("Username");
lblUsername.setBounds(34, 44, 72, 18);
contentPane.add(lblUsername); lblPassword = new JLabel("Password");
lblPassword.setBounds(34, 99, 72, 18);
contentPane.add(lblPassword); lblwham = new JLabel("\u4F5C\u8005:wh4am1 QQ:1976604307");
lblwham.setBounds(232, 247, 198, 18);
contentPane.add(lblwham);
}
}
mailSend.java
源代码如上
其中,账号密码通过PasswordAuthentication类型返回
再传入session中去
再new一个Transpor对象来装入session
接下来就是链接SMTP来判断账号密码的正确
利用Transport对象的connect去链接
若验证失败,则会返回一个AuthenticationFailedException异常
这时候我们可以用try-catch来捕获这个异常
看完我们的代码就可以发现,我们在connect后面,还有一个新的对象建立
学过Jframe的人就知道,这是新建了一个窗口
而这个窗口类就是SendText
而新建的窗口,就是我们登陆成功后,编写邮件正文的窗口
代码如下
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton; public class SendText extends JFrame { /**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private Session session;
private Transport ts;
private String Forme;
private JTextField textField_1; /**
* Launch the application.
*/
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// SendText frame = new SendText();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// } public static MimeMessage creatMail(Session session,String Forme,String toe,String title,String text) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(Forme));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toe));
message.setSubject(title);
message.setText(text);
//message.setContent("<h1>Hello,World!</h1>","text/html");
return message;
} /**
* Create the frame.
* @throws NoSuchProviderException
*/
public SendText(Session s,String forme) throws Exception {
this.session = s;
this.Forme = forme;
this.ts = session.getTransport(); addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
dispose();
}
}); setTitle("SendText");
setResizable(false);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(200, 300, 510, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null); JTextArea textArea = new JTextArea();
textArea.setLineWrap(true); JPopupMenu popupMenu = new JPopupMenu();
addPopup(textArea, popupMenu); JMenuItem mntmCopy = new JMenuItem("\u590D\u5236");
mntmCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.copy();
}
});
popupMenu.add(mntmCopy); JMenuItem menuItem = new JMenuItem("\u7C98\u8D34");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.paste();
}
});
popupMenu.add(menuItem); JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(0, 13, 492, 227);
contentPane.add(scrollPane); JLabel lblSendTo = new JLabel("Send to");
lblSendTo.setBounds(83, 301, 72, 18);
contentPane.add(lblSendTo); textField = new JTextField();
textField.setBounds(159, 298, 198, 24);
contentPane.add(textField);
textField.setColumns(10); JPopupMenu popupMenu_1 = new JPopupMenu();
addPopup(textField, popupMenu_1); JMenuItem menuItem_1 = new JMenuItem("\u590D\u5236");
menuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.copy();
}
});
popupMenu_1.add(menuItem_1); JMenuItem menuItem_2 = new JMenuItem("\u7C98\u8D34");
menuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.paste();
}
});
popupMenu_1.add(menuItem_2); JButton btnSend = new JButton("Send");
btnSend.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
ts.connect();
JOptionPane.showMessageDialog(null, "邮件已成功发送!", "Message", JOptionPane.INFORMATION_MESSAGE);
Message message = creatMail(session,Forme,textField.getText(),textField_1.getText(),textArea.getText());
ts.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ts.close();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnSend.setBounds(169, 351, 113, 27);
contentPane.add(btnSend); JLabel lblMailTitle = new JLabel(" Mail title ");
lblMailTitle.setBounds(61, 270, 96, 18);
contentPane.add(lblMailTitle); textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(159, 267, 198, 24);
contentPane.add(textField_1); JPopupMenu popupMenu_2 = new JPopupMenu();
addPopup(textField_1, popupMenu_2); JMenuItem menuItem_3 = new JMenuItem("\u590D\u5236");
menuItem_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.copy();
}
});
popupMenu_2.add(menuItem_3); JMenuItem menuItem_4 = new JMenuItem("\u7C98\u8D34");
menuItem_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.paste();
}
});
popupMenu_2.add(menuItem_4);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
SendText.java
竟然前面的窗口我们能登陆成功,那么我们接下来要做的就是发送邮件
聪明的人就知道,我在创建窗口的时候传入了两个参数
这样做的好处就是不需要在这个窗口又建一遍session,而后面的String,是为了不让发件者再输入一遍自己的邮箱
万事俱备,我们就准备发件
跳过去看看
可以看到这又是一个链接,但这次链接不一样,后面建立了一个Message类,并调用了creatMail方法
转过去看之后发现,这时设置邮件正文和标题的方法
并最后用sendMessage方法发送邮件
下面就将整个工程打包jar
首先打开工程-〉鼠标右键选中Export
然后再选择
Next
至此,程序整体逻辑已完结。
下面附上测试效果。
如果邮件里面没有看到邮件,可以看看是不是SMTP协议没开,获知是在垃圾箱里。