java在linux下调用smtp协议发送邮件

java在linux下调用smtp协议发送邮件,第1张

你只是发邮件不是做邮件服务器吧?这样的话 在linux和window没有区别不然java都不好意思说自己是跨平台的了
JAVA邮件发送的大致过程是这样的的:
1、构建一个继承自javaxmailAuthenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。
2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。
3、通过构建的properties文件和javaxmailAuthenticator具体类来创建一个javaxmailSession。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。
4、构建邮件内容,一般是javaxmailinternetMimeMessage对象,并指定发送人,收信人,主题,内容等等。
5、使用javaxmailTransport工具类发送邮件。
参考地址>我给你提供一个我在项目里面实际使用的代码
这是我基于一个网上的代码自己修改封装过来的
你可以参考一下
/
  
  @author Sglee
  
 /
public class SimpleMail {

private static String encode = null;
static {
if ("\\"equals(Fileseparator)) {
encode = "GBK";
} else {
encode = "UTF-8";
}
}

/
  以文本格式发送邮件
  
  @param mailInfo
  @return
 /
public static boolean sendTextMail(MailInfo mailInfo) {
for (int i = 0; i < 3; i++) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties properties = mailInfogetProperties();
if (mailInfoisValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfogetUsername(),
mailInfogetPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = SessiongetDefaultInstance(properties,
authenticator);
if (mailInfoisDebug()) {
sendMailSessionsetDebug(true);
}
try {
Message mailMessage = new MimeMessage(sendMailSession);// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfogetFromAddress());// 创建邮件发送者地址
mailMessagesetFrom(from);// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfogetToAddress());//
// 创建邮件的接收者地址
// mailMessagesetRecipient(MessageRecipientTypeTO, to);//
// 设置邮件消息的接收者
mailMessagesetRecipients(MessageRecipientTypeTO,
wrapAddress(mailInfogetToAddress()));
// InternetAddress ms = new
// InternetAddress(mailInfogetMsAddress());
// mailMessagesetRecipient(MessageRecipientTypeBCC, ms); //
// 密送人
mailMessagesetRecipients(MessageRecipientTypeBCC,
wrapAddress(mailInfogetMsAddress()));
mailMessagesetSubject(mailInfogetSubject());// 设置邮件消息的主题
mailMessagesetSentDate(new Date());// 设置邮件消息发送的时间
// mailMessagesetText(mailInfogetContent());//设置邮件消息的主要内容
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();// 创建一个包含附件内容的MimeBodyPart
// 设置HTML内容
messageBodyPartsetContent(mailInfogetContent(),
"text/html; charset=" + encode);
mainPartaddBodyPart(messageBodyPart);
// 存在附件
String[] filePaths = mailInfogetAttachFileNames();
if (filePaths != null && filePathslength > 0) {
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart();
File file = new File(filePath);
if (fileexists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file);// 得到数据源
messageBodyPart
setDataHandler(new DataHandler(fds));// 得到附件本身并至入BodyPart
messageBodyPartsetFileName("=" + encode + "B"
+ filegetName());// 得到文件名同样至入BodyPart
mainPartaddBodyPart(messageBodyPart);
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessagesetContent(mainPart);
Transportsend(mailMessage);// 发送邮件
return true;
} catch (Exception e) {
eprintStackTrace();
try {
javautilconcurrentTimeUnitSECONDSsleep(5);
} catch (Exception e2) {
e2printStackTrace();
}
}
}
return false;
}
/
  将string[]包装成EmailAddress
  @param mailInfo
  @return
  @throws AddressException
 /
private static Address [] wrapAddress(String[] adds) throws AddressException {
// String[] adds = mailInfogetToAddress();
if(adds == null || addslength == 0){
return null;
}
Address []to = new Address[addslength];
for(int i = 0;i<addslength;i++){
to[i]=new InternetAddress(adds[i]);
}
return to;
}
/
  以HTML格式发送邮件
  
  @param mailInfo
  @return
 /
public static boolean sendHtmlMail(MailInfo mailInfo) {
for (int i = 0; i < 3; i++) {

// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties properties = mailInfogetProperties();
if (mailInfoisValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfogetUsername(),
mailInfogetPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = SessiongetDefaultInstance(properties,
authenticator);
if (mailInfoisDebug()) {
sendMailSessionsetDebug(true);
}
try {
Message mailMessage = new MimeMessage(sendMailSession);// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfogetFromAddress());// 创建邮件发送者地址
mailMessagesetFrom(from);// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfogetToAddress());//
// 创建邮件的接收者地址
// mailMessagesetRecipient(MessageRecipientTypeTO, to);//
// 设置邮件消息的接收者
mailMessagesetRecipients(MessageRecipientTypeTO,
wrapAddress(mailInfogetToAddress()));
// InternetAddress ms = new
// InternetAddress(mailInfogetMsAddress());
// mailMessagesetRecipient(MessageRecipientTypeBCC, ms); //
// 密送人
mailMessagesetRecipients(MessageRecipientTypeBCC,
wrapAddress(mailInfogetMsAddress()));
mailMessagesetSubject(mailInfogetSubject());// 设置邮件消息的主题
mailMessagesetSentDate(new Date());// 设置邮件消息发送的时间
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();// 创建一个包含HTML内容的MimeBodyPart
// 设置HTML内容
messageBodyPartsetContent(mailInfogetContent(),
"text/html; charset=" + encode);
mainPartaddBodyPart(messageBodyPart);
// 存在附件
String[] filePaths = mailInfogetAttachFileNames();
if (filePaths != null && filePathslength > 0) {
sunmiscBASE64Encoder enc = new sunmiscBASE64Encoder();
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart();
File file = new File(filePath);
if (fileexists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file);// 得到数据源
messageBodyPart
setDataHandler(new DataHandler(fds));// 得到附件本身并至入BodyPart
messageBodyPartsetFileName("=" + encode + "B"
+ encencode(EmailFileNameConvertchangeFileName(filegetName())getBytes())
+ "=");// 得到文件名同样至入BodyPart
mainPartaddBodyPart(messageBodyPart);
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessagesetContent(mainPart);
Transportsend(mailMessage);// 发送邮件
return true;
} catch (Exception e) {
eprintStackTrace();
try {
javautilconcurrentTimeUnitSECONDSsleep(5);
} catch (Exception e2) {
e2printStackTrace();
}
}

}
return false;
}
}
/
  封装邮件的基本信息
  
  @author Sglee
  
 /
public class MailInfo implements Serializable{
/
  
 /
private static final long serialVersionUID = -3937199642590071261L;
private String mailServerHost;// 服务器ip
private String mailServerPort;// 端口
private long timeout;// 超时时间
private String fromAddress;// 发送者的邮件地址
private String[] toAddress;// 邮件接收者地址
private String[] msAddress;// 密送地址
private String username;// 登录邮件发送服务器的用户名
private String password;// 登录邮件发送服务器的密码
private boolean validate = false;// 是否需要身份验证
private String subject;// 邮件主题
private String content;// 邮件内容
private String[] attachFileNames;// 附件的文件地址
private boolean debug;// 调试模式
public Properties getProperties() {
Properties p = new Properties();
pput("mailsmtphost", thismailServerHost);
pput("mailsmtpport", thismailServerPort);
pput("mailsmtpauth", validate  "true" : "false");
pput("mailsmtptimeout", thistimeout);
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
thismailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
thismailServerPort = mailServerPort;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
thisfromAddress = fromAddress;
}
public String[] getToAddress() {
return toAddress;
}
public void setToAddress(String[] toAddress) {
thistoAddress = toAddress;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
thisusername = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
thispassword = password;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
thisvalidate = validate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
thissubject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
thiscontent = content;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] attachFileNames) {
thisattachFileNames = attachFileNames;
}
public void setMsAddress(String[] msAddress) {
thismsAddress = msAddress;
}
public String[] getMsAddress() {
return msAddress;
}
public void setDebug(boolean debug) {
thisdebug = debug;
}
public boolean isDebug() {
return debug;
}
public void setTimeout(long timeout) {
thistimeout = timeout;
}
public long getTimeout() {
return timeout;
}
}
public class MyAuthenticator extends Authenticator {
private String username = null;
private String password = null;
public MyAuthenticator() {
};
public MyAuthenticator(String username, String password) {
thisusername = username;
thispassword = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
注意一下:
Myeclipse自带的JavaEE5jar和java mail会发生冲突
找到ME下的javeee包
D:\MyEclipse 85\Common\plugins\comgenuitececlipsej2eedtcore_850me201003231033\data\libraryset\EE_5\javaeejar
用rar等解压工具解开javaeejar,删除里面的javax\mail文件夹(可以先备份javaeejar)
也即,以后都不能使用javaeejar里面的邮件api发送邮件了

不知有帮助没有了
<%@ page
import=" javaxmail, javaxmailinternet, javaxactivation,javautil"
%>
<html>
<head>
<TITLE>JSP meets JavaMail, what a sweet combo</TITLE>
</HEAD>
<BODY>
<%
try{
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;
sendMailSession = SessiongetInstance(props, null);
propsput("mailsmtphost", "smtpjspinsidercom");
Message newMessage = new MimeMessage(sendMailSession);
newMessagesetFrom(new InternetAddress(requestgetParameter("from")));
newMessagesetRecipient(MessageRecipientTypeTO, new InternetAddress(requestgetParameter("to")));
newMessagesetSubject(requestgetParameter("subject"));
newMessagesetSentDate(new Date());
newMessagesetText(requestgetParameter("text"));
transport = sendMailSessiongetTransport("smtp");
transportsend(newMessage);
%>
<P>Your mail has been sent</P>
<%
}
catch(MessagingException m)
{
outprintln(mtoString());
}
%>
</BODY>
</HTML>

1 import orgquartzJob;
2 import orgquartzJobExecutionContext;
3 import orgquartzJobExecutionException;
4 import javautilCalendar;
5 import javatextSimpleDateFormat;
6 import javautilDate;
7 import javalangInterruptedException;
8 import javautilRandom;
9 import javautilProperties;
10 import javaxmail;
11 import javaxmailinternet;
12 public class MailJob implements Job
13 {
14 public void execute(JobExecutionContext context)
15 throws JobExecutionException {
16 //收件人,标题和文本内容
17 String to = "#######@126com";//填写你要发给谁
18 String title = createTitle();
19 String text = createText();
20 //设置属性
21 Properties props = new Properties();
22 //QQ邮箱发件的服务器和端口
23 propsput("mailsmtphost", "smtpqqcom");
24 propsput("mailsmtpsocketFactoryport", "465");
25 propsput("mailsmtpsocketFactoryclass", "javaxnetsslSSLSocketFactory");
26 propsput("mailsmtpauth", "true");
27 propsput("mailsmtpport", "25");
28 Session session = SessiongetDefaultInstance(props,
29 new javaxmailAuthenticator() {
30 protected PasswordAuthentication getPasswordAuthentication() {
31 //填写你的qq邮箱用户名和密码
32 return new PasswordAuthentication("@qqcom", "###%%%");
33 }
34 });
35 MimeMessage message = new MimeMessage(session);
36 //这里用flag来标记是否发件成功(有时候会连不上服务器),
37 //如果没有,继续发送,直到发送成功为止。
38 int flag = 0;
39 {
40 try {
41 //设置发件人,收件人,主题和文本内容,并发送
42 messagesetFrom(new InternetAddress("@qqcom"));//填写你自己的qq邮箱,和上面相同
43 messageaddRecipient(MessageRecipientTypeTO, new InternetAddress(to));
44 messagesetSubject(title);
45 messagesetText(text);
46 Systemoutprintln("Preparing sending mail");
47 Systemoutprintln(text);
48 Transportsend(message);
49 flag = 1;
50 Systemoutprintln("message sent successfully");
51 } catch(Exception e) {
52 flag = 0;
53 }
54 } while(flag == 0);
55 }
56 //下面的两个方法,用来随机组合标题和文本内容。文本内容由四部分随机组合。
57 //产生标题
58 public String createTitle() {
59 String[] titles = {"love", "I love you", "Miss you", "My baby"};
60 Random randT = new Random(SystemcurrentTimeMillis());
61 String title = titles[randTnextInt(titleslength)];
62 return title;
63 }
64 //产生文本内容,文本内容由四部分随机组合得到。
65 public String createText() {
66 //名字纯属虚构,如有雷同(肯定会有),纯属巧合。
67 String[] parts1 = {"晓静,你好。", "晓静,你还好吗?", "晓静,你那边天气怎么样?"};
68 String[] parts2 = {
69 "距离上次见面,我感觉已经好长时间了。",
70 "流去的时间磨不去我对你的爱。",
71 "我仍然记得你在天安门前的那一抹笑容。"
72 };
73 String[] parts3 = {"今天,我大胆地追求你。",
74 "我不怕大胆地对你说,我爱你。",
75 "此刻,月亮代表我的心。"
76 };
77 String[] parts4 = {
78 "未来,我的心依旧属于你。",
79 "好想在未来陪你一起慢慢变老,当然在我心中你不会老。"
80 };
81 Random randT = new Random(SystemcurrentTimeMillis());
82 String text = parts1[randTnextInt(parts1length)]
83 + parts2[randTnextInt(parts2length)]
84 + parts3[randTnextInt(parts3length)]
85 + parts4[randTnextInt(parts4length)];
86 return text;
87 }
88
89 }
复制代码
触发器的代码:
复制代码
1 import orgquartzCronScheduleBuilder;
2 import orgquartzJobBuilder;
3 import orgquartzJobDetail;
4 import orgquartzScheduler;
5 import orgquartzTrigger;
6 import orgquartzTriggerBuilder;
7 import orgquartzimplStdSchedulerFactory;
8 import javautilRandom;
9 public class CronTriggerExample
10 {
11 public static void main( String[] args ) throws Exception
12 {
13 //创建工作对象
14 JobDetail job = JobBuildernewJob(MailJobclass)
15 withIdentity("dummyJobName", "group1")build();
16 //为了立即测试,可以使用下面的代码,每隔5秒钟执行一次
17 //int secDelta = 5;
18 //Trigger trigger = TriggerBuilder
19 // newTrigger()
20 // withIdentity("dummyTriggerName", "group1")
21 // withSchedule(
22 // CronScheduleBuildercronSchedule("0/" + secDelta + " "))
23 // build();
24 //在每天早上的9点多(不超过3分钟)执行
25 Random rand = new Random(SystemcurrentTimeMillis());
26 int secDelta = randnextInt(60 3);
27 //创建触发器对象
28 Trigger trigger = TriggerBuilder
29 newTrigger()
30 withIdentity("dummyTriggerName", "group1")
31 withSchedule(
32 CronScheduleBuildercronSchedule(secDelta + " 0 9 SUN-SAT"))
33 build();
34
35 Scheduler scheduler = new StdSchedulerFactory()getScheduler();
36 schedulerstart();
37 //将触发器与工作关联起来
38 schedulerscheduleJob(job, trigger);
39 }
40 }
发邮件依赖的包:activationjar,mailjar
将发邮件依赖的包和quartz下载得到的lib路径下的jar包全部放在mylib路径下,mylib路径与java文件位于同一个目录。编译和运行时,可以使用命令:
set classpath=mylib/;;
javac CronTriggerExamplejava
java CronTriggerExample

06年的sun科技日的时候,sun的演讲团,讲师沈卓立拿这个做了一个例子。主要的美观处理还是多层的贴图效果,如果谁有源码也可以送我一份。这个个人觉得有点难度……
至于简单邮件收发,例子到处都是,我这里现在有个正用的发生例子。接收就是处理pop3,然后拆分邮件体和邮件标题,附件等一些功能。
private MimeMessage mimeMsg; // MIME邮件对象
private Session sessions; // 邮件会话对象
private Properties props; // 系统属性
private boolean needAuth = false; // smtp是否需要认证
private String username = ""; // smtp认证用户名和密码
private String password = "";
private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
public SendMail() {
// setSmtpHost(getConfigmailHost);//如果没有指定邮件服务器,就从getConfig类中获取
createMimeMessage();
}
public SendMail(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
}
public void setSmtpHost(String hostName) {
if (props == null)
props = SystemgetProperties(); // 获得系统属性对象
propsput("mailsmtphost", hostName); // 设置SMTP主机
}
public boolean createMimeMessage() {
try {
sessions = SessiongetDefaultInstance(props, null); // 获得邮件会话对象
} catch (Exception e) {
eprintStackTrace();
return false;
}
try {
mimeMsg = new MimeMessage(sessions); // 创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch (Exception e) {
Systemerrprintln("创建MIME邮件对象失败!" + e);
return false;
}
}
public void setNeedAuth(boolean need) {
if (props == null)
props = SystemgetProperties();
if (need) {
propsput("mailsmtpauth", "true");
} else {
propsput("mailsmtpauth", "false");
}
}
public void setNamePass(String name, String pass) {
username = name;
password = pass;
}
public boolean setSubject(String mailSubject) {
try {
mimeMsgsetSubject(mailSubject);
return true;
} catch (Exception e) {
Systemerrprintln("设置邮件主题发生错误!");
return false;
}
}
public boolean setBody(String mailBody) {
try {
BodyPart bp = new MimeBodyPart();
bpsetContent(
"<meta >

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/10287341.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-07
下一篇 2023-05-07

发表评论

登录后才能评论

评论列表(0条)

保存