81,092
社区成员
发帖
与我相关
我的任务
分享
HtmlEmail email = new HtmlEmail();
email.setHostName("192.168.1.123");//服务器
email.setSmtpPort(25);
email.addTo("bcrcw@test.cn");//设置接收方
email.setFrom("782213194@qq.com");//设置发送方
email.getMailSession().getProperties().put("mail.smtp.auth", "false");
email.setCharset("UTF-8");//设置编码
email.setSubject("你好");
email.setHtmlMsg("<html><body>hello</body></html>");
email.setPopBeforeSmtp(true,"test.cn","bcrcw","123456");
if(!email.send().isEmpty()){
System.out.println("success");
}else{
System.out.println("error");
}
package action;
import java.util.Arrays;
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.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
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;
public class SendMailGUI{
/** serialVersionUID */
String imagePath = null;
javax.swing.JProgressBar bar = new javax.swing.JProgressBar();
public int run(String from, String to, String title, String content) {
MailMessage mesg = new MailMessage(from,to,title,content);
try
{
sendMail(mesg);
return 1;
}catch (Exception ex){
return 0;
}
}
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());
}
}
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", "false");
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());
MimeMultipart mimeMultipart = new MimeMultipart();
//内容部分.
BodyPart contentBodyPart = new MimeBodyPart();
contentBodyPart.setContent(mesg.getContent(), "text/html;charset=GB2312");
mimeMultipart.addBodyPart(contentBodyPart);
// add the attachments
mimeMessage.setContent(mimeMultipart);
mimeMessage.saveChanges();
//发送
Transport.send(mimeMessage);
}
public byte[] readFile(String file){
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
int bytesRead;
byte buffer[] = new byte[1024 * 1024];
while ((bytesRead = fis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
Arrays.fill(buffer, (byte) 0);
}
}catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return bos.toByteArray();
}
}
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;
}
}
//--------------------------
类:ByteArrayDataSource
package action;
import java.io.*;
import javax.activation.*;
public class ByteArrayDataSource implements DataSource{
/*** Data to write. */
private byte[] _data;
/*** Content-Type. */
private String _type;
/* Create a datasource from an input stream */
public ByteArrayDataSource(InputStream is,String type)
{
_type = type;
try
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
int ch;
http://www.mscto.com
// XXX : must be made more efficient by
// doing buffered reads, rather than one byte reads
while ((ch = is.read()) != -1)
os.write(ch);
_data = os.toByteArray();
}
catch (IOException ioe)
{
}
}
/* Create a datasource from a byte array */
public ByteArrayDataSource(byte[] data,String type)
{
_data = data;
_type = type;
}
/* Create a datasource from a String */
public ByteArrayDataSource(String data,String type)
{
try
{
// Assumption that the string contains only ascii
// characters ! Else just pass in a charset into this
// constructor and use it in getBytes()
_data = data.getBytes("iso-8859-1");
}
catch (UnsupportedEncodingException uee)
{
}
_type = type;
}
public InputStream getInputStream()
throws IOException
{
if (_data == null)
throw new IOException("no data");
return new ByteArrayInputStream(_data);
}
public OutputStream getOutputStream()
throws IOException
{
throw new IOException("cannot do this");
}
public String getContentType()
{
return _type;
}
public String getName()
{
return "dummy";
}
}
HtmlEmail email = new HtmlEmail();
email.setHostName("test.cn");//服务器
email.setSmtpPort(25);
email.setAuthentication("bcrcw","123456");//验证用户
email.addTo("782213194@qq.com");//设置接收方
email.setFrom("bcrcw@test.cn");//设置发送方
email.getMailSession().getProperties().put("mail.smtp.auth", "true");
email.setCharset("UTF-8");//设置编码
email.setSubject("你好");
email.setHtmlMsg("<html><body>hello</body></html>");
if(!email.send().isEmpty()){
System.out.println("success");
}else{
System.out.println("error");
}