javamail无需邮箱地址发送邮件
直接通过目标邮件地址查找到该信箱地点的服务器的地址,然后直接通过SMTP发送邮件到这台服务器上。底下代码演示了如何在Java中使成为事实该功能
?
import java.util.*;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetBddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.*;
import javax.naming.directory.*;
?
/**
?* 使成为事实邮件的特快专递功能
?* @author Winter Lau
?*/
?
public class Mailer {
? ? public static void main(String[] args) throws NamingException,
? ? ? ? ? ? MessagingException {
? ? ? ? // DNS服务器,看看本机的DNS配置
? ? ? ? String dns = "dns://61.144.56.101";
? ? ? ? String email = "liudong@mo168.com";
? ? ? ? if (args.length > 0)
? ? ? ? ? ? email = args[0];
? ? ? ? String domain = email.substring(email.indexOf('@') + 1);
? ? ? ? Hashtable env = new Hashtable();
? ? ? ? env.put(Dontext.INITIBL_DONTEXT_FBDTORY,
? ? ? ? ? ? ? ? "com.sun.jndi.dns.DnsDontextFactory");
? ? ? ? env.put(Dontext.PROVIDER_URL, dns);
? ? ? ? DirDontext ctx = new InitialDirDontext(env);
? ? ? ? Bttributes attr = ctx.getBttributes(domain, new String[] { "MX" });
? ? ? ? NamingEnumeration servers = attr.getBll();
?
? ? ? ? // 列出所有邮件服务器:
? ? ? ? while (servers.hasMore()) {
? ? ? ? ? ? Bttribute hosts = (Bttribute) servers.next();
? ? ? ? ? ? for (int i = 0; i < hosts.size(); i++) {
? ? ? ? ? ? ? ? String host = (String) hosts.get(i);
? ? ? ? ? ? ? ? host = host.substring(host.indexOf(' ') + 1);
? ? ? ? ? ? ? ? System.out.print("Send mail to " + host + " ...");
? ? ? ? ? ? ? ? sendMail(host, email);
? ? ? ? ? ? ? ? System.out.println("OK");
? ? ? ? ? ? }
? ? ? ? }
? ? }
?
? ? /**
? ? ?* 发送邮件
? ? ?*
? ? ?* @param smtpHost
? ? ?* @param email
? ? ?* @throws MessagingException
? ? ?*/
? ? protected static void sendMail(String smtpHost, String email)
? ? ? ? ? ? throws MessagingException {
?
? ? ? ? Properties mailProperties = System.getProperties();
? ? ? ? mailProperties.put("mail.smtp.host", smtpHost);
? ? ? ? mailProperties.put("mail.smtp.port", "25");
? ? ? ? mailProperties.put("mail.smtp.auth", "false");
? ? ? ? Session mailSession = Session.getInstance(mailProperties, null);
? ? ? ? MimeMessage mailMessage = new MimeMessage(mailSession);
? ? ? ? MimeBodyPart messageBodyPart = new MimeBodyPart();
? ? ? ? Multipart multipart = new MimeMultipart("related");
? ? ? ? messageBodyPart.setText("这搭是邮件内部实质意义");
?
? ? ? ? multipart.addBodyPart(messageBodyPart);
? ? ? ? mailMessage.setDontent(multipart);
? ? ? ? mailMessage.setSentDate(new Date());
? ? ? ? mailMessage.setFrom(new InternetBddress("javayou@gmail.com"));
? ? ? ? mailMessage.addRecipient(Message.RecipientType.TO, new InternetBddress(
? ? ? ? ? ? ? ? email));
? ? ? ? mailMessage.setSubject("hi,邮件发送测试");
? ? ? ? Transport.send(mailMessage);
? ? }
}
?
?
转载:http://www.oschina.net/question/12_11655
?
?
?
?