`
tanglei198577
  • 浏览: 59913 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

send email by java api

    博客分类:
  • java
阅读更多

First ,create a properies file for config file,

EmailSMTP=mail.*.com
FromAddress=email@*.com
EmailUser=email
EmailPassWord=email
ToAddress=tom@*.com;ray@*.com
FileName=H://*.txt;H://*.txt
ShowFileName=*.txt

 then the java code should be:

package com.test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class Mail {

	public static void main(String[] args){
		
		String EmailSMTP="";
		String FromAddress="";
		String EmailUser="";
		String EmailPassWord="";
		String ToAddress = "";
		String FileName = "";
		String ShowFileName = "";
		
		//get the config file
		try {
			InputStream in = new BufferedInputStream(new FileInputStream("email.properties"));
			Properties p = new Properties();
			p.load(in);
			ToAddress = p.getProperty("ToAddress");
			FileName = p.getProperty("FileName");
			ShowFileName = p.getProperty("ShowFileName");		
			EmailSMTP = p.getProperty("EmailSMTP");
			FromAddress = p.getProperty("FromAddress");
			EmailUser = p.getProperty("EmailUser");
			EmailPassWord = p.getProperty("EmailPassWord");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Properties props = System.getProperties();
		props.setProperty("mail.smtp.host", EmailSMTP);
		props.put("mail.smtp.auth", "true");
		
		Session s = Session.getInstance(props);
		s.setDebug(true);
		MimeMessage message = new MimeMessage(s);
		
		try {
			//from server
			InternetAddress from = new InternetAddress(FromAddress);
			message.setFrom(from);
			//define receiver
			if(ToAddress.trim().length()>0){
				String[] arr = ToAddress.split(";");
				int receiverCount = arr.length;
				if(receiverCount>0){
					InternetAddress[] address = new InternetAddress[receiverCount];
					for(int i=0;i<receiverCount;i++){
						address[i] = new InternetAddress(arr[i]);
					}
					message.addRecipients(Message.RecipientType.TO, address);
				}else{
					System.out.println("None receiver!Check the 'ToAddress' please!");
					System.exit(0);
				}
			}
			message.setSubject("test");
			String content = "automatically send by java api";
			message.setContent(content, "text/html;charset=GBK");
			
			//add the attachment
			Multipart multipart = new MimeMultipart();
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setText("Automatically send by JAVA API!");
			multipart.addBodyPart(messageBodyPart);
			if(FileName.trim().length()>0){
				String[] arr = FileName.split(";");
				int attCount = arr.length;
				if(attCount>0){
					for(int i=0;i<attCount;i++){
						messageBodyPart = new MimeBodyPart();
						DataSource source = new FileDataSource(arr[i]);
						messageBodyPart.setDataHandler(new DataHandler(source));
						messageBodyPart.setFileName(arr[i]);
						multipart.addBodyPart(messageBodyPart);
					}
				}else{
					System.out.println("None attachment!");
					System.exit(0);
				}
			}
			message.setContent(multipart);
			message.saveChanges();
			Transport transport = s.getTransport("smtp");
			transport.connect(EmailSMTP, EmailUser, EmailPassWord);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 export as a jar file.

Find this jar and extract it,go to "/META-INF/" to find the MANIFEST.MF file, then add "Main-Class: com.test.Mail" with the enter as the end.

use the jar command to create a new jar: jar -cvfm test.jar manifest.mf com

then put activation.jar;mail.jar;test.jar;runJava.bat;email.properties in the same folder,the runJava.bat file is:

java -cp test.jar;mail.jar;activation.jar com.test.Mail

 then we got a bat file,so we can use the timer or assignmanagerment to choose email send time

分享到:
评论

相关推荐

    Java邮件开发Fundamentals of the JavaMail API

    receiving messages by dividing the API into two parts: * The first part of the API is the focus of this course --basically, how to send and receive messages independent of the provider/protocol. ...

    Java应用发送邮件demo

    JavaMail是Java编程语言中用于处理电子邮件的API,它提供了丰富的功能,允许开发者在应用程序中发送、接收和处理邮件。本教程将详细讲解如何利用JavaMail API实现一个发送163邮箱邮件的示例。 首先,你需要在项目中...

    java结合email实现自动推送功能

    在Java中,我们可以使用JavaMail API来实现邮件发送。以下是一段基础的邮件发送代码: - `Authenticator`类用于认证邮件发送者,它包含`username`和`password`,并提供`getPasswordAuthentication()`方法返回认证...

    公司招聘异地笔试题.doc

    List&lt;WebElement&gt; emailTitles = driver.findElements(By.className("email_title")); for (WebElement title : emailTitles) { System.out.println(title.getText()); } driver.quit(); } } ``` ### 知识点...

    Android Mail发送邮件依赖的包

    首先,JavaMail API是Java平台上广泛使用的邮件处理库,但在原生的Android系统中并未直接包含。为了在Android应用中发送邮件,开发者通常需要引入一个专门为Android优化的JavaMail库,如Apache Commons Net或者开源...

    VB编程资源大全(英文源码 网络)

    url.zip Worldwide list of URL extensions by country&lt;END&gt;&lt;br&gt;29 , EmailChk.zip This Application checks for unread email using outlook. MS Agent will popup to announce how many unread mails you ...

    ZendFramework中文文档

    9.3.2. Zend_Date by Example 9.3.2.1. Ouput a Date 9.3.2.2. Setting a Date 9.3.2.3. Adding and Subtracting Dates 9.3.2.4. Comparation of dates 9.4. Zend_Date API Overview 9.4.1. Zend_Date Options...

    Visual C++ 编程资源大全(英文源码 其它)

    anirocx.zip AnirOCX - An OCX to add remote control support to your Windows applications(36KB)&lt;END&gt;&lt;br&gt;51,smtpsend.zip A shareware ISAPI module to send Internet (SMTP) email(104KB)&lt;END&gt;&lt;br&gt;52,...

    jfinalpluginsjfinal-dreampie.zip

     htmlEmail.send();  } catch (EmailException e) {  e.printStackTrace();  }  }  }, Akka.system&#40;&#41;.dispatcher()); 10.自定义验证码,可以自定义使用字符或者数字,颜色和样式可以自调 ...

    freemarker总结

    JAVA模版引擎Freemarker常用标签(一) 1. if指令 这是一个典型的分支控制指令,该指令的作用完全类似于Java语言中的if,if指令的语法格式如下: &lt;#if condition&gt;... &lt;#elseif condition&gt;... &lt;#elseif condition&gt;......

Global site tag (gtag.js) - Google Analytics