邮件发送代码示例


public class Authen extends Authenticator {
	   String userName=null;   
	    String password=null;   
	        
	    public Authen(){   
	    }   
	    public Authen(String username, String password) {    
	        this.userName = username;    
	        this.password = password;    
	    }    
	    protected PasswordAuthentication getPasswordAuthentication(){   
	        return new PasswordAuthentication(userName, password);   
	    }  
}


public class SenderInfo {
	 private String mailServerHost;    
	    private String mailServerPort = "25";    
	    // 邮件发送者的地址    
	    private String fromAddress;    
	    // 邮件接收者的地址    
	    private String toAddress;    
	    // 登陆邮件发送服务器的用户名和密码    
	    private String userName;    
	    private String password;    
	    // 是否需要身份验证    
	    private boolean validate = true;    
	    // 邮件主题    
	    private String subject;    
	    // 邮件的文本内容    
	    private String content;    
	    // 邮件附件的文件名    
	    private String[] attachFileNames;      
	    /**   
	      * 获得邮件会话属性   
	      */    
	    public Properties getProperties(){    
	      Properties p = new Properties();    
	      p.put("mail.smtp.host", this.mailServerHost);    
	      p.put("mail.smtp.port", this.mailServerPort);    
	      p.put("mail.smtp.auth", validate ? "true" : "false");    
	      return p;    
	    }    
	    public String getMailServerHost() {    
	      return mailServerHost;    
	    }    
	    public void setMailServerHost(String mailServerHost) {    
	      this.mailServerHost = mailServerHost;    
	    }   
	    public String getMailServerPort() {    
	      return mailServerPort;    
	    }   
	    public void setMailServerPort(String mailServerPort) {    
	      this.mailServerPort = mailServerPort;    
	    }   
	    public boolean isValidate() {    
	      return validate;    
	    }   
	    public void setValidate(boolean validate) {    
	      this.validate = validate;    
	    }   
	    public String[] getAttachFileNames() {    
	      return attachFileNames;    
	    }   
	    public void setAttachFileNames(String[] fileNames) {    
	      this.attachFileNames = fileNames;    
	    }   
	    public String getFromAddress() {    
	      return fromAddress;    
	    }    
	    public void setFromAddress(String fromAddress) {    
	      this.fromAddress = fromAddress;    
	    }   
	    public String getPassword() {    
	      return password;    
	    }   
	    public void setPassword(String password) {    
	      this.password = password;    
	    }   
	    public String getToAddress() {    
	      return toAddress;    
	    }    
	    public void setToAddress(String toAddress) {    
	      this.toAddress = toAddress;    
	    }    
	    public String getUserName() {    
	      return userName;    
	    }   
	    public void setUserName(String userName) {    
	      this.userName = userName;    
	    }   
	    public String getSubject() {    
	      return subject;    
	    }   
	    public void setSubject(String subject) {    
	      this.subject = subject;    
	    }   
	    public String getContent() {    
	      return content;    
	    }   
	    public void setContent(String textContent) {    
	      this.content = textContent;    
	    }    

	}


/**
 * 简单邮件(不带附件的邮件)发送器
 */
public class SimpleMailSender {
	/**
	 * 以文本格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件的信息
	 */
	public boolean sendTextMail(SenderInfo mailInfo) {
		// 判断是否需要身份认证
		Authen authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份认证,则创建一个密码验证器
			authenticator = new Authen(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
			// 设置邮件消息的主要内容
			String mailContent = mailInfo.getContent() ;
			mailMessage.setText(mailContent);
			// 发送邮件
			Transport.send(mailMessage);
			Log.i("sendMail", "sendMail成功");
			return true;
		} catch (MessagingException ex) {

			Log.e("sendMail", ex.getMessage());
		}
		return false;
	}

	/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 */
	public static boolean sendHtmlMail(SenderInfo mailInfo) {
		// 判断是否需要身份认证
		Authen authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份认证,则创建一个密码验证器
		if (mailInfo.isValidate()) {
			authenticator = new Authen(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			// Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
			// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			mailMessage.setContent(mainPart);
			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}

}




#include <windows.h> #include <winsock.h> #include <assert.h> #include <iostream> #include <string> #include <stdio.h> #include <ctime> #pragma comment(lib,"WS2_32.lib") using namespace std; //base64编码 string Base64Encode(LPCTSTR lpszSrc); //base64解码 string Base64Decode(LPCTSTR lpszSrc); int main() { //1.首先需要连接邮件服务器 这里用socket 邮件服务器端口 25 WSADATA Wsa; //进行WINSOCK的设置 WSAStartup(0x0101,&Wsa); SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_IP); SOCKADDR_IN sin; LPHOSTENT lphost = gethostbyname("smtp.163.com");//这里是用网易的邮件服务器 也可以修改 if(lphost) sin.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; else { printf("%s\n","获取地址失败"); return 1; } sin.sin_family = AF_INET; //注意邮件服务器的侦听端口 25 sin.sin_port = htons(IPPORT_SMTP); //连接服务器 if(connect(s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR) { printf("%s\n","连接错误"); return 1; } printf("%s\n","连接成功"); //接收服务器初次回应 char buff[1024]; memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); /////上面已经完成连接了///// string szLine="\r\n";//相当于你按下回车 //2.现在就是和服务器对话了 //问候服务器 string szHelo = "HELO smtp.163.com" + szLine; printf("我说:%s\n",szHelo.c_str()); send(s,szHelo.c_str(),szHelo.length(),0); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //请求验证用户密码(需要编码) string szAL = "auth login" + szLine; //发送验证命令 printf("我说:%s\n",szAL.c_str()); send(s,szAL.c_str(),szAL.length(),0); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); //服务器会回答说 可以输入帐号 //发送帐号 string szUser; cout<<Base64Decode((LPCTSTR)(buff+4)); cin>>szUser; szUser = Base64Encode(szUser.c_str()) + szLine; //对输入的帐号进行base64编码 send(s,szUser.c_str(),szUser.length(),0); //发送帐号 printf("我说:%s\n",szUser.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); //服务器会回答说 可以输入密码 //发送密码 string szPsw; cout<<Base64Decode((LPCTSTR)(buff+4)); cin>>szPsw; szPsw = Base64Encode(szPsw.c_str()) + szLine; //对输入的密码进行base64编码 send(s,szPsw.c_str(),szPsw.length(),0); //发送密码 printf("我说:%s\n",szPsw.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //然后可以用你登陆的邮箱给其他邮箱发邮件了 string szFrom,szTo; cout<<"from:";//你自己的邮箱 cin>>szFrom; cout<<"to:"; //发送给谁 cin>>szTo; //发送者的地址 string From = "mail from:<"+szFrom+ ">"+ szLine; //收信者地址 string To = "rcpt to:<" + szTo +">" + szLine; //现在确定看谁发的邮件 往哪发 send(s,From.c_str(),From.length(),0);//from printf("我说:%s\n",From.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //只是用来暂停一下而已 按任意字母继续 send(s,To.c_str(),To.length(),0); //to printf("我说:%s\n",To.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //资料应该都看过了吧命令里的data输入后 表示输入邮件内容了 send(s,"data\r\n",6,0); //DATA 命令发送 printf("我说:%s\n","data"); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //邮件 下面的信息都是当作内容处理 //邮件头 string szFrom_in = "from:"+szFrom + szLine; string szTo_in = "to:"+szTo + szLine; //发送日期 string szDate_in="Date: Sat, 20 Aug 2011 13:39:29 +0800" + szLine;//这里我就直接写上去日期了 为了方便 //邮件标题 string szSubject_in = "Subject:我是邮件标题" + szLine; //邮件正文 string szBody_in = "我就是传说中的邮件体" + szLine; string szContent = szFrom_in + szTo_in + szDate_in + szSubject_in; szContent += szLine;//添加一个空白行 szContent += szBody_in; //上面是最基本的格式// send(s,szContent.c_str(),szContent.length(),0); //szContent printf("我说:%s\n",szContent.c_str()); memset(buff,0,sizeof(buff)); // recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); getchar(); //发送完了说明下结束 send(s,".\r\n",3,0); //说明内容结束了 printf("我说:%s\n","."); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //退出服务器连接 send(s,"quit\r\n",6,0); //退出 printf("我说:%s\n","quit"); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s 发送邮件成功\n",buff); return 0; } 等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值