发送email

来源:互联网 发布:简书 知乎同时 编辑:程序博客网 时间:2024/05/21 22:06
 

 

做用户注册时免不了要让用户使用邮件激活账号,这时就得用到使用程序发邮件的技术了。如下是我在项目中常用的发邮件的方法:

【C#】

 1    usingSystem.Net.Mail;
 2    usingSystem.Net;
 3
 4    publicclassEmailEntity
 5    {
 6        privateMailMessage mm;
 7
 8        ///<summary>
 9        ///发送邮件
10        ///</summary>
11        publicvoidsendMessage()
12        {
13
14            //指定发件人的邮箱地址
15            MailAddress fromAddress = newMailAddress("abc@163.com");
16            //指定收件人的邮箱地址
17            MailAddress toAddress = newMailAddress("efg@qq.com");
18            //创建邮件对象
19            mm = newMailMessage(fromAddress, toAddress);
20            //添加一个密送的邮件地址
21            mm.Bcc.Add(newMailAddress("xiuxiu@qq.com"));
22            //添加一个抄送的邮件地址
23            mm.CC.Add(newMailAddress("me@qq.com"));
24            //指定邮件标题的编码格式
25            mm.SubjectEncoding = Encoding.UTF8;
26            //设置邮件标题
27            mm.Subject = "我是标题";
28            //指定邮件正文编码

29            mm.BodyEncoding = Encoding.UTF8;
30            //指定邮件正文是否text/html类型
31            mm.IsBodyHtml = true;
32            //设置邮件正文内容
33            mm.Body = "<span style='color:#ff0000;font-weight:bold;'>我爱秀秀!</span>";
34            //创建附件
35            Attachment file = newAttachment(AppDomain.CurrentDomain.BaseDirectory+"xiuxiu.jpg");
36            //设置附件的创建日期
37            file.ContentDisposition.CreationDate = DateTime.Now;
38            //设置附件的类型
39            file.ContentType = newSystem.Net.Mime.ContentType("image/jpeg");
40            //将附件添加到邮件中
41            mm.Attachments.Add(file);
42
43            //指定邮件发送服务器的地址和端口号
44            SmtpClient sc = newSmtpClient("smtp.163.com", 25);
45            //指定发件人的身份验证信息
46            sc.Credentials = newNetworkCredential("abc", "123456");
47            //sc.Send(mm);
48            //注册异步发送事件
49            sc.SendCompleted += newSendCompletedEventHandler(sc_SendCompleted);
50            //开始执行异步发送邮件
51            sc.SendAsync(mm, null);
52        }
53        //异步发送邮件完成时处理事件
54        voidsc_SendCompleted(objectsender, System.ComponentModel.AsyncCompletedEventArgs e)
55        {
56            if(mm != null)

57            {
58                mm.Dispose();//释放资源
59            }
60            if(e.Cancelled)
61            {
62                Console.WriteLine("用户已取消!");
63            }
64            elseif(e.Error != null)
65            {
66                Console.WriteLine("发送失败,原因如下:"+ e.Error.Message);
67            }
68            else
69            {
70                Console.WriteLine("发送成功!");
71            }
72        }
73    }

【Java】

  1importjava.util.Date;
  2importjava.util.Properties;
  3importjavax.mail.Authenticator;
  4importjavax.mail.PasswordAuthentication;
  5importjavax.mail.Message.RecipientType;
  6importjavax.mail.MessagingException;
  7importjavax.mail.Session;
  8importjavax.mail.Transport;
  9importjavax.mail.internet.AddressException;
 10importjavax.mail.internet.InternetAddress;
 11importjavax.mail.internet.MimeMessage;
12importjavax.mail.internet.MimeMultipart;

 13
 14/**
 15 * 邮件实体类,封装了有关发送邮件的方法。
 16 * @authorxxxxxx
 17 *
 18 */
 19publicclassEmailEntity {
 20
 21    privateMimeMessage msg;
 22
 23    /**
 24     * 初始化邮件实体
 25     *
 26     * @paramfromDomin
 27     *            发件人邮件服务器域名,如:163.com、qq.com
 28     * @paramuserName
 29     *            发件人用户名,如:qmail、20082345
 30     * @parampassword
 31     *            发件人密码
 32     * @paramtoAddress
 33     *            收件人邮箱地址,如:200712345@qq.com
 34     */
 35    publicEmailEntity(String fromDomin, String userName, String password) {
 36        Properties p = newProperties();
 37        //设置邮件发送服务器的地址
 38        p.setProperty("mail.host", "smtp." + fromDomin);
 39        //设置使用权限验证
 40        p.setProperty("mail.smtp.auth", "true");
 41        //设置用户身份验证凭据
 42        Session ses = Session.getDefaultInstance(p, newMyAuthentic

ator(userName, password));
 43        //ses.setDebug(true);//设置是否出现回显信息
 44        //创建邮件实体
 45        msg = newMimeMessage(ses);
 46        try{
 47            //设置发件人邮箱地址
 48            msg.setFrom(newInternetAddress(userName + "@" + fromDomin));
 49        } catch(AddressException e) {
 50            e.printStackTrace();
 51        } catch(MessagingException e) {
 52            e.printStackTrace();
 53        }
 54    }
 55
 56    /**
 57     * 发送消息
 58     *
 59     * @paramtitle
 60     *            邮件标题
 61     * @paramcontent
 62     *            邮件正文
 63     * @paramtype
 64     *            正文的类型,如:text/html、text/plain
 65     * @return
 66     */
 67    publicbooleansendMessage(String toAddress, String title, String content, String type) {
 68
 69        try{
 70            //设置发件人邮箱地址
 71            msg.setRecipient(RecipientType.TO, newInternetAddress

 (toAddress));
 72            //设置邮件发送日期
 73            msg.setSentDate(newDate());
 74            //设置邮件标题
 75            msg.setSubject(title);
 76            //设置邮件正文
 77            msg.setContent(content, type);
 78            //开始发送邮件
 79            Transport.send(msg);
 80            returntrue;
 81        } catch(MessagingException ex) {
 82            ex.printStackTrace();
 83            returnfalse;
 84        }
 85    }
 86
 87    /**
 88     * 发送带附件的邮件
 89     * @paramtoAddress 收件人的邮箱地址,如suxibo@126.com
 90     * @paramtitle 邮件标题
 91     * @paramcontent 邮件正文,包括附件
 92     * @paramtype 邮件正文的类型
 93     * @return
 94     */
 95    publicbooleansendEmailWithAttachment(String toAddress, String title, MimeMultipart content, String type) {
 96        try{
 97            msg.setRecipient(RecipientType.TO, newInternetAddress(toAddress));
 98            msg.setSentDate(newDate());
 99            msg.setSubject(title);
100            msg.setContent(content);
101            Transport.send(msg);

102            returntrue;
103        } catch(MessagingException ex) {
104            ex.printStackTrace();
105            returnfalse;
106        }
107    }
108}
109
110//用户身份验证凭据类
111classMyAuthenticator extendsAuthenticator {
112    
113    privateString _userName;
114    privateString _password;
115    
116    publicMyAuthenticator(String userName,String password){
117        this._userName = userName;
118        this._password = password;
119    }
120    
121    @Override
122    publicPasswordAuthentication getPasswordAuthentication() {
123        //返回使用了用户名和密码的身份验证凭据
124        returnnewPasswordAuthentication(_userName, _password);
125    }
126}

原创粉丝点击