java代码实现SMTP发送邮件的三种解决方案

by 好大一小白 2012.7.23 12:14

方式一:

依赖的jar包:mail.jar

代码:

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MyTest {

public boolean sendMail(boolean textOrHtml) {
try {
Properties props = new Properties();
Authenticator auth = new MyAutherticator("邮箱帐号","密码");//邮件服务器认证
props.put("mail.smtp.host", "smtp.sina.com.cn");
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props,auth);
//设置session,和邮件服务器进行通信
MimeMessage message = new MimeMessage(session);
message.setSubject("邮件的主题");
message.setSentDate(new Date());//设置邮件发送日期

Address address = new InternetAddress("帐号","我的邮件");
message.setFrom(address);//设置邮件发送者的地址

Address toaddress = new InternetAddress("收件人邮箱");//设置邮件接收者的地址
message.addRecipient(Message.RecipientType.TO,toaddress);

if(textOrHtml)message.setText("邮件内容mail's content....."); //内容为文本
else {//内容为html
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();

//发送的内容还有超链接,或者直接一个网址 收件箱怎么都收不到,为什么?!被当作垃圾邮件过滤了?!
String myHtmlContent ="<font color=red>你好</font>" ;
//+"http://www.guihua.org";
// +"<a href=\"http://www.baidu.com\">链接</a>";
html.setContent(myHtmlContent, "text/html; charset=utf-8");
mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容
message.setContent(mainPart);
}

Transport.send(message);//发送邮件
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
MyTest a = new MyTest();
if(a.sendMail(true))System.out.println("send text mail successfully!!");
if(a.sendMail(false))System.out.println("send html mail successfully!!");
}
}

MyAutherticator类的代码:

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAutherticator extends Authenticator {
String username = "";
String password = "";

public Email_Autherticator() {
super();
}
public Email_Autherticator(String user,String pwd){
super();
this.username = user;
this.password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}

############################################################################################

方式二:

依赖的jar包:mail.jar spring.jar commons-logging.jar

代码如下:

import java.io.File;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SendFileMail3 {

public static boolean sendMailWithFiles() {

try {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

// 设置邮件服务器
senderImpl.setHost("smtp.sina.com.cn");
senderImpl.setUsername("帐号");
senderImpl.setPassword("密码");

MimeMessage mailMessage = senderImpl.createMimeMessage();

// true表示开始附件模式
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

// 设置收件人,寄件人
messageHelper.setTo("收件人邮箱");
messageHelper.setFrom("帐号");
messageHelper.setSubject("测试邮件!");

// true 表示启动HTML格式的邮件
messageHelper.setText("<html><head></head><body><h1>你好:附件!!" +
"</h1><a href=\"http://www.baidu.com\">邮件测试内容</a></body></html>", true);
//这儿就能加超链接了

FileSystemResource file1 = new FileSystemResource(new File("文件地址"));
FileSystemResource file2 = new FileSystemResource(new File("文件二地址"));
// 添加两个附件
messageHelper.addAttachment("文件", file1);

//防止中文文件名出现乱码
messageHelper.addAttachment(MimeUtility.encodeWord("中文名"), file2);

senderImpl.send(mailMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
if(sendMailWithFiles())System.out.println("邮件发送成功.....");
}
}

#####################################################################

方式3:

依赖的jar包:mail.jar commons-email.jar

示例代码:

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

//依赖jar:commons-email.jar,activation.jar,mail.jar
public class SendFileMail4 {

public static void sendMutiMessage() {

MultiPartEmail email = new MultiPartEmail();
try {
email.setHostName("smtp.sina.com.cn");
email.setCharset("utf-8");
email.addTo("接收方邮箱地址");
email.setFrom("邮箱用户名");
email.setAuthentication(, "密码");
email.setSubject("这是一封测试邮件");

email.setMsg("邮件测试内容 "); //不支持html

String[] attachs = new String[] { "D:/myfine.jpg",
"http://www.google.com.hk/intl/zh-CN/images/logo_cn.png" };

for (int i = 0; i <attachs.length;i++) //添加多个附件
{
EmailAttachment attachment = new EmailAttachment();
//判断当前这个文件路径是否在本地 如果是:setPath 否则 setURL;
if (attachs[i].startsWith("http")) {
try {
attachment.setURL(new URL(attachs[i]));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
else attachment.setPath(attachs[i]);

attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
//attachment.setName("bulktree"); //附件的文件名
email.attach(attachment);
}

email.send(); // 发送
} catch (EmailException e) {
e.printStackTrace();
}
}
public static void send()
{
SimpleEmail email = new SimpleEmail();
email.setTLS(true); //是否TLS校验,某些邮箱需要TLS安全校验,同理可能有SSL校验
// email.setSSL(true);
// email.setSslSmtpPort("465"); //设定SSL端口

email.setHostName("smtp.sina.com.cn");
email.setAuthentication("tangliang2046", "*******password********");

try
{
email.addTo("接收方邮箱地址"); //接收方
email.setFrom("邮箱地址"); //发送方
email.setSubject("Java发送邮件测试"); //标题
// email.setCharset("GB2312"); //设置Charset 这儿或者设置成UTF-8
// email.addCc(""); //抄送方
// email.addBcc(""); //秘密抄送方
email.setMsg("这是一封Java程序发出的测试邮件。"); //内容
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}


public static void send3()

{
HtmlEmail email = new HtmlEmail();
//HtmlEmil:用来发送HTML格式的email,除了有MultipartEmail的所有能力,还可以发送内嵌的图象
email.setTLS(true);
email.setHostName("smtp.sina.com.cn");
email.setAuthentication("用户帐号", "密码");

try
{
email.addTo("接收方邮件地址");
email.setFrom("用户帐号"); //发送方
email.setSubject("Java发送邮件测试"); //标题
email.setCharset("GB2312"); //设置Charset 这儿或者设置成UTF-8
//email.setHtmlMsg("这是一封<font color=red>Java程序</font>发出的测试邮件。");

//内嵌图象
URL url = new URL("http://www.google.com.hk/intl/zh-CN/images/logo_cn.png");
String cid = email.embed(url, "google's picture");
email.setHtmlMsg("<html>google <img src=\"cid:" + cid + "\"></html>");
email.setTextMsg("Your email client does not support HTML messages");

email.send();
System.out.println("发送成功。。。。。");
} catch (EmailException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
//sendMutiMessage();
send3();
}
}

 

注意:使用方案一,无法发送带有链接地址的邮件。邮件可以发送成功,但是无法收到。

PS:使用新浪的smtp这样,腾讯的可以正常收到,

如果有链接地址,建议使用方案二。

Tags: , , , ,

JAVA | 服务器 | TOMCAT

不允许评论

微信赞

本站统计

36 篇文章
5 个单页
12 条评论
12 次评分
1306548 次访问
访问统计开始于 2010年4月24日
平均日访问 223 次
当前 4 人在线

声明

本博所有网友评论不代表本博立场,版权归其作者所有。 
苏ICP备09004001号
Powered by BlogYi.net  edit by 1wanweb.com
© Copyright 2008-2017