/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMail {
private String host;
private String from;
private String to;
private String subject;
private String content;
private boolean authentication;
private String username;
private String password;
public void sendMail(String host, String from, String to, String subject,
String content, boolean authentication, String username,
String password) throws MessagingException {
Properties props = System.getProperties();
if(this.host.indexOf("smtp.gmail.com")>=0)//注意此处 加了判断 因为gmail的端口是465
{
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
}else{
props.put("mail.smtp.host", host);
if (!authentication) {
props.put("mail.smtp.auth", "false");
} else {
props.put("mail.smtp.auth", "true");
}
}
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setContent(content, "text/html;charset=gb2312");
if (authentication) {
Transport smtp = null;
try {
smtp = session.getTransport("smtp");
smtp.connect(host, username, password);
smtp.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
smtp.close();
}
} else {
Transport.send(message);
}
}
public void send() throws MessagingException {
host = "smtp.sina.com";//smtp服务器
from = "******@sina.com";
to = "to@sina.com"; //发送给谁
subject = "just for test"; //标题
content = "Beijing Olympic"; //内容
authentication = true;
username = "******@sina.com"; // 登陆邮件发送服务器的用户名
password = "******"; // 登陆邮件发送服务器的密码
sendMail(host, from, to, subject, content, authentication, username,
password);
}
public static void main(String args[]) throws MessagingException {
JavaMail jm = new JavaMail();
jm.send();
}
}
java发邮件 javamail +mail.jar
3星 · 超过75%的资源 需积分: 10 41 浏览量
2010-06-19
13:41:54
上传
评论
收藏 394KB RAR 举报
masrue
- 粉丝: 4
- 资源: 12
最新资源
- Q1.py
- 企业政府灵智电子政务网站系统-lingzhi.rar
- Thinkphp内核开发Lsky Pro兰空图床网站源码.rar
- 基于FPGA(XC6SLX9)+SDRAM+AD7829多通道数据采集板硬件(原理图+PCB)工程文件.zip
- 阿里巴巴精准测试体系:基于代码链路分析的性能优化方案
- mmexport1714217773503.jpg
- 【图片网盘外链系统5.0】全新前端UI界面设计 支持图片违规检测网站自适应H5源码.rar
- jsp+sql的BBS论坛系统.zip
- 网盘外链PHP开发彩虹网盘外链程序源码.rar
- 2023年最新文件快递柜系统网站源码 保护用户隐私的匿名口令分享和临时文件分享功能.rar
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈