整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

C#发送邮件-C#教程

C#发送邮件-C#教程

何利用C#实现邮件发送功能?闲话不多说请看代码:

public static void SendMail(MyEmail email)

{

//发送验证邮箱邮件。

//1.创建邮件

MailMessage mail=new MailMessage();

mail.Subject=email.Title;

mail.SubjectEncoding=System.Text.Encoding.UTF8;

mail.Body=email.Content;

mail.BodyEncoding=System.Text.Encoding.UTF8;

mail.IsBodyHtml=true;

//发件人

mail.From=new MailAddress("cxx7177@163.com", email.Subject);

//收件人

mail.To.Add(new MailAddress(email.SendEmail));

//创建一个发送邮件的类

SmtpClient client=new SmtpClient("smtp.163.com", 25);

client.Credentials=new NetworkCredential("帐号", "密码");

client.Send(mail);

}

public class MyEmail

{

//string content,string sendEmail,string Uid,string subject

public string Content { get; set; }

public string SendEmail { get; set; }

public string Subject { get; set; }

public string Title { get; set; }

}

}

当然本代码可用于:C#发送邮件,asp.net发送邮件,.net发送邮件,希望可以帮到您

www.chengxiaoxiao.com/

 前言

  邮件是许多项目里都需要用到的功能,之前一直都是用JavaMail来发,现在Spring框架为使用JavaMailSender接口发送电子邮件提供了一个简单的抽象,Spring Boot为它提供了自动配置以及启动模块。springboot参考手册介绍:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-email

  作为发送方,首先需要开启POP3/SMTP服务,登录邮箱后前往设置进行开启,开启后取得授权码。

  POP3 :
  POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循POP3协议的接收邮件服务器,用来接收电子邮件的。
  

  SMTP:
  SMTP 的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。是一组用于从源地址到目的地址传输邮件的规范,通过来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。


  代码编写

  maven引包,其中,邮件模板需要用到thymeleaf

        <!-- springboot mail -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- springboot web(MVC)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- springboot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


  appliaction.propertise配置文件

#设置服务端口
server.port=10010

# Email (MailProperties)
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=huanzi.qch@qq.com #发送方邮件名 
spring.mail.password=#授权码 
spring.mail.properties.mail.smtp.auth=true 
spring.mail.properties.mail.smtp.starttls.enable=true 
spring.mail.properties.mail.smtp.starttls.required=true


  SpringBootMailServiceImpl.java

@Service
class SpringBootMailServiceImpl implements SpringBootMailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送方
     */
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送简单邮件
     *
     * @param to      接收方
     * @param subject 邮件主题
     * @param text    邮件内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String text) {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);

        mailSender.send(message);
    }

    /**
     * 发送HTML格式的邮件
     *
     * @param to      接收方
     * @param subject 邮件主题
     * @param content HTML格式的邮件内容
     * @throws MessagingException
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message=mailSender.createMimeMessage();
        //true表示需要创建一个multipart message
        MimeMessageHelper helper=new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

    /**
     * 发送HTML格式的邮件,并可以添加附件
     * @param to      接收方
     * @param subject 邮件主题
     * @param content HTML格式的邮件内容
     * @param files   附件
     * @throws MessagingException
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, List<File> files) throws MessagingException {
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        //添加附件
        for(File file : files){
            helper.addAttachment(file.getName(), new FileSystemResource(file));
        }

        mailSender.send(message);
    }
}


  测试controller

    @Autowired
    private SpringBootMailService springBootMailService;

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/index")
    public String index() throws MessagingException {
        //简单邮件
        springBootMailService.sendSimpleMail("1726639183@qq.com","Simple Mail","第一封简单邮件");

        //HTML格式邮件
        Context context=new Context();
        context.setVariable("username","我的小号");
        springBootMailService.sendHtmlMail("1726639183@qq.com","HTML Mail",templateEngine.process("mail/mail",context));

        //HTML格式邮件,带附件
        Context context2=new Context();
        context2.setVariable("username","我的小号(带附件)");
        ArrayList<File> files=new ArrayList<>();
        files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试.txt"));
        files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试2.txt"));
        springBootMailService.sendAttachmentsMail("1726639183@qq.com","Attachments Mail",templateEngine.process("mail/attachment",context2),files);

        return "hello springboot!";
    }


  两个html模板,路径:myspringboot\src\main\resources\templates\mail\

  mail.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Mail Templates</title>
</head>
<body>
    <h3><span th:text="${username}"></span>,你好!</h3>
    <p style="color: red;">这是一封HTML格式的邮件。</p>
</body>
</html>

  attachment.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Mail Templates Accessory</title>
</head>
<body>
    <h3><span th:text="${username}"></span>,你好!</h3>
    <p>这是一封HTML格式的邮件。请收下附件!</p>
</body>
</html>


  效果

  Simple Mail

  HTML Mail


  Attachments Mail



  后记

  本文章部分参考:https://www.cnblogs.com/yangtianle/p/8811732.html


  代码开源

  代码已经开源、托管到我的GitHub、码云:

  GitHub:https://github.com/huanzi-qch/springBoot

  码云:https://gitee.com/huanzi-qch/springBoot



版权声明

作者:huanzi-qch

出处:https://www.cnblogs.com/huanzi-qch

若标题中有“转载”字样,则本文版权归原作者所有。若无转载字样,本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.

子邮件能让访问者方便地向网站提供反馈或联系信息。它可以自动填写抄送和密件抄送,甚至能自动填充主题行。下面介绍如何定制 Mailto功能。

实现 Mailto的基本html代码:

<a href="mailto:stephen.zhaoyf@163.com">点击这里发邮件给站长!</a>

当访问者点击这个链接时,会调用他们客户端的email程序,并在收件人框中自动填上收件人的地址。下面,我们将分以下几步介绍如何增加mailto的功能。

第一步:

创建一个基本的mailto,包含收件人的地址。注意:后面的参数符需要采用英文的符号

第二步:

在收件人地址后用“?cc="开头,你可以填写抄送(CC:)地址,下面这个例子将实现该功能:

<a href="mailto:stephen.zhaoyf@163.com?cc=guest@163.net">点击这里发邮件给站长并“抄送”给guest!</a>

第三步:

就像下面这个例子一样,紧跟着抄送地址之后,写上"&bcc=",就可以填上密件抄送(BCC)地址 (在添加这些功能时,第一个功能以"?"开头,后面的以"&"开头)

<a href="mailto:stephen.zhaoyf@163.com?cc=guest@163.net&bcc=guest@163.net">点击这里发邮件给站长并同时“抄送”、“暗送”给guest!</a>

还可以同时发信给N个人!地址之间用逗号分开:

<a href="mailto:stephen.zhaoyf@163.com,guest@163.net,guest1@163.net">点击这里同时发送N个邮件!</a>

第四步:

用?subject=或者&subject(当前面还有抄送或暗送时使用)填上主题。

<a href="mailto:stephen.zhaoyf@163.com?subject=不好意思,只是做个实验!">点击这里发送有主题的邮件!</a>

更加夸张的是连邮件内容都可以事先写好!

<a href="mailto:stephen.zhaoyf@163.com?subject=不好意思,只是做个实验!&body=特别无聊,所以发现这么一个功能">这个邮件地址、内容都有了!以后可就懒了!</a>

下面我们来总结一下:

Mailto后为收件人地址,cc后为抄送地址,bcc后为密件抄送地址,subject后为邮件的主题,body后为邮件的内容,如果Mailto后面同时有多个参数的话,第一个参数必须以“?”开头,后面的每一个都以“&”开头。下面是一个完整的实例:

Mailto:aaa@xxx.com?cc=bbb@yyy.com&bcc=ccc@zzz.com&subject=主题&body=邮件内容

乱码问题:

比如调用个下载程序,当下载的URL中含有中文的时候,无法下载,比如:

http://www.huachu.com.cn/itbook/booklist.asp?tsmc=汇编

试着用 .net 中的 Server.UrlEncode 函数进行转换。但是这样仍然不行,试验了很久也没有找到原因。后来怀疑 ASP.net中的Server.UrlEncode函数和ASP中的Server.URLEncode函数返回的值竟然不一样。一实验,竟然确实是。

试验代码:

ASP.net 中 如下代码?

Response.Write(Server.UrlEncode("汇编")); ?返回: %e6%b1%87%e7%bc%96

ASP 中 如下代码 Response.Write Server.URLEncode("汇编")?? 返回: %BB%E3%B1%E0

产生这个问题的原因:ASP.net 中的 Server.UrlEncode 默认是按照 UTF-8 编码方式进行处理的。而ASP中是按照本地设置编码方式进行处理的。

如果你在 ASP.net 下采用如下的编码: ASP 和 ASP.net 的结果就会一样:

Response.Write(HttpUtility.UrlEncode("汇编",Encoding.Default));

采用:Response.Write(HttpUtility.UrlEncode("汇编",Encoding.UTF8));? 返回的就是 Response.Write(Server.UrlEncode("汇编"));?? 返回的结果。