当前位置: 首页>>代码示例>>Golang>>正文


Golang MIMEHeader.Set方法代码示例

本文整理汇总了Golang中net/textproto.MIMEHeader.Set方法的典型用法代码示例。如果您正苦于以下问题:Golang MIMEHeader.Set方法的具体用法?Golang MIMEHeader.Set怎么用?Golang MIMEHeader.Set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/textproto.MIMEHeader的用法示例。


在下文中一共展示了MIMEHeader.Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: WriteRevisionAsPart

// Adds a new part to the given multipart writer, containing the given revision.
// The revision will be written as a nested multipart body if it has attachments.
func (db *Database) WriteRevisionAsPart(revBody Body, isError bool, compressPart bool, writer *multipart.Writer) error {
	partHeaders := textproto.MIMEHeader{}
	docID, _ := revBody["_id"].(string)
	revID, _ := revBody["_rev"].(string)
	if len(docID) > 0 {
		partHeaders.Set("X-Doc-ID", docID)
		partHeaders.Set("X-Rev-ID", revID)
	}

	if hasInlineAttachments(revBody) {
		// Write as multipart, including attachments:
		// OPT: Find a way to do this w/o having to buffer the MIME body in memory!
		var buffer bytes.Buffer
		docWriter := multipart.NewWriter(&buffer)
		contentType := fmt.Sprintf("multipart/related; boundary=%q",
			docWriter.Boundary())
		partHeaders.Set("Content-Type", contentType)
		db.WriteMultipartDocument(revBody, docWriter, compressPart)
		docWriter.Close()
		content := bytes.TrimRight(buffer.Bytes(), "\r\n")

		part, err := writer.CreatePart(partHeaders)
		if err == nil {
			_, err = part.Write(content)
		}
		return err
	} else {
		// Write as JSON:
		contentType := "application/json"
		if isError {
			contentType += `; error="true"`
		}
		return writeJSONPart(writer, contentType, revBody, compressPart)
	}
}
开发者ID:joeljeske,项目名称:sync_gateway,代码行数:37,代码来源:attachment.go

示例2: writeJSONPart

func writeJSONPart(writer *multipart.Writer, contentType string, body Body, compressed bool) (err error) {
	bytes, err := json.Marshal(body)
	if err != nil {
		return err
	}
	if len(bytes) < kMinCompressedJSONSize {
		compressed = false
	}

	partHeaders := textproto.MIMEHeader{}
	partHeaders.Set("Content-Type", contentType)
	if compressed {
		partHeaders.Set("Content-Encoding", "gzip")
	}
	part, err := writer.CreatePart(partHeaders)
	if err != nil {
		return err
	}

	if compressed {
		gz := gzip.NewWriter(part)
		_, err = gz.Write(bytes)
		gz.Close()
	} else {
		_, err = part.Write(bytes)
	}
	return
}
开发者ID:joeljeske,项目名称:sync_gateway,代码行数:28,代码来源:attachment.go

示例3: CreateMailMessage

// CreateMailMessage creates a (plain) SMTP email with body and
// optional attachments.
func CreateMailMessage(body []byte, att []*MailAttachment) ([]byte, error) {
	buf := new(bytes.Buffer)
	wrt := multipart.NewWriter(buf)
	buf.WriteString(
		"MIME-Version: 1.0\n" +
			"Content-Type: multipart/mixed;\n" +
			" boundary=\"" + wrt.Boundary() + "\"\n\n" +
			"This is a multi-part message in MIME format.\n")
	hdr := textproto.MIMEHeader{}
	hdr.Set("Content-Type", "text/plain; charset=ISO-8859-15")
	hdr.Set("Content-Transfer-Encoding", "utf-8")
	pw, err := wrt.CreatePart(hdr)
	if err != nil {
		return nil, err
	}
	pw.Write(body)

	for _, a := range att {
		pw, err = wrt.CreatePart(a.Header)
		if err != nil {
			return nil, err
		}
		pw.Write(a.Data)
	}
	wrt.Close()
	return buf.Bytes(), nil
}
开发者ID:bfix,项目名称:gospel,代码行数:29,代码来源:smtp.go

示例4: WriteMultipartDocument

// Writes a revision to a MIME multipart writer, encoding large attachments as separate parts.
func (db *Database) WriteMultipartDocument(body Body, writer *multipart.Writer, compress bool) {
	// First extract the attachments that should follow:
	following := []attInfo{}
	for name, value := range BodyAttachments(body) {
		meta := value.(map[string]interface{})
		var info attInfo
		info.contentType, _ = meta["content_type"].(string)
		info.data, _ = decodeAttachment(meta["data"])
		if info.data != nil && len(info.data) > kMaxInlineAttachmentSize {
			info.name = name
			following = append(following, info)
			delete(meta, "data")
			meta["follows"] = true
		}
	}

	// Write the main JSON body:
	writeJSONPart(writer, "application/json", body, compress)

	// Write the following attachments
	for _, info := range following {
		partHeaders := textproto.MIMEHeader{}
		if info.contentType != "" {
			partHeaders.Set("Content-Type", info.contentType)
		}
		partHeaders.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", info.name))
		part, _ := writer.CreatePart(partHeaders)
		part.Write(info.data)
	}
}
开发者ID:jnordberg,项目名称:sync_gateway,代码行数:31,代码来源:attachment.go

示例5: parseMIMEParts

// parseMIMEParts will recursively walk a MIME entity and return a []mime.Part containing
// each (flattened) mime.Part found.
// It is important to note that there are no limits to the number of recursions, so be
// careful when parsing unknown MIME structures!
func parseMIMEParts(hs textproto.MIMEHeader, b io.Reader) ([]*part, error) {
	var ps []*part
	// If no content type is given, set it to the default
	if _, ok := hs["Content-Type"]; !ok {
		hs.Set("Content-Type", defaultContentType)
	}
	ct, params, err := mime.ParseMediaType(hs.Get("Content-Type"))
	if err != nil {
		return ps, err
	}
	// If it's a multipart email, recursively parse the parts
	if strings.HasPrefix(ct, "multipart/") {
		if _, ok := params["boundary"]; !ok {
			return ps, ErrMissingBoundary
		}
		mr := multipart.NewReader(b, params["boundary"])
		for {
			var buf bytes.Buffer
			p, err := mr.NextPart()
			if err == io.EOF {
				break
			}
			if err != nil {
				return ps, err
			}
			if _, ok := p.Header["Content-Type"]; !ok {
				p.Header.Set("Content-Type", defaultContentType)
			}
			subct, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
			if strings.HasPrefix(subct, "multipart/") {
				sps, err := parseMIMEParts(p.Header, p)
				if err != nil {
					return ps, err
				}
				ps = append(ps, sps...)
			} else {
				// Otherwise, just append the part to the list
				// Copy the part data into the buffer
				if _, err := io.Copy(&buf, p); err != nil {
					return ps, err
				}
				ps = append(ps, &part{body: buf.Bytes(), header: p.Header})
			}
		}
	} else {
		// If it is not a multipart email, parse the body content as a single "part"
		var buf bytes.Buffer
		if _, err := io.Copy(&buf, b); err != nil {
			return ps, err
		}
		ps = append(ps, &part{body: buf.Bytes(), header: hs})
	}
	return ps, nil
}
开发者ID:louisyoo,项目名称:email,代码行数:58,代码来源:email.go

示例6: renderPartsToWriter

func renderPartsToWriter(parts cloudInitParts, writer io.Writer) error {
	mimeWriter := multipart.NewWriter(writer)
	defer mimeWriter.Close()

	writer.Write([]byte(fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\n", mimeWriter.Boundary())))

	for _, part := range parts {
		header := textproto.MIMEHeader{}
		if part.ContentType == "" {
			header.Set("Content-Type", "text/plain")
		} else {
			header.Set("Content-Type", part.ContentType)
		}

		if part.Filename != "" {
			header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, part.Filename))
		}

		if part.MergeType != "" {
			header.Set("X-Merge-Type", part.MergeType)
		}

		partWriter, err := mimeWriter.CreatePart(header)
		if err != nil {
			return err
		}

		_, err = partWriter.Write([]byte(part.Content))
		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:chrusty,项目名称:terraform-multipart-userdata,代码行数:35,代码来源:resource.go

示例7: appendPart

func appendPart(w *multipart.Writer, headers func(h textproto.MIMEHeader), body string) {
	if body == "" {
		return
	}

	h := textproto.MIMEHeader{}
	h.Set("Content-Transfer-Encoding", "quoted-printable")
	headers(h)
	partW, err := w.CreatePart(h)
	log.Panice(err, "create MIME part")
	quoW := quotedprintable.NewWriter(partW)
	defer quoW.Close()
	io.WriteString(quoW, body)
}
开发者ID:hlandau,项目名称:degoutils,代码行数:14,代码来源:authhandlers.go

示例8: storeMessage

// store message, unpack attachments, register with daemon, send to daemon for federation
// in that order
func (self *nntpConnection) storeMessage(daemon *NNTPDaemon, hdr textproto.MIMEHeader, body io.Reader) (err error) {
	var f io.WriteCloser
	msgid := getMessageID(hdr)
	if msgid == "" {
		// drop, invalid header
		log.Println(self.name, "dropping message with invalid mime header, no message-id")
		_, err = io.Copy(Discard, body)
		return
	} else if ValidMessageID(msgid) {
		f = daemon.store.CreateFile(msgid)
	} else {
		// invalid message-id
		log.Println(self.name, "dropping message with invalid message-id", msgid)
		_, err = io.Copy(Discard, body)
		return
	}
	if f == nil {
		// could not open file, probably already storing it from another connection
		log.Println(self.name, "discarding duplicate message")
		_, err = io.Copy(Discard, body)
		return
	}
	path := hdr.Get("Path")
	hdr.Set("Path", daemon.instance_name+"!"+path)
	// now store attachments and article
	err = writeMIMEHeader(f, hdr)
	if err == nil {
		err = daemon.store.ProcessMessageBody(f, hdr, body)
		if err == nil {
			// tell daemon
			daemon.loadFromInfeed(msgid)
		}
	}
	f.Close()
	if err != nil {
		// clean up
		if ValidMessageID(msgid) {
			DelFile(daemon.store.GetFilename(msgid))
		}
	}
	return
}
开发者ID:ZiRo-,项目名称:srndv2,代码行数:44,代码来源:nntp.go

示例9: createFormFile

func createFormFile(writer *multipart.Writer, fieldname, filename string) {
	// Try to open the file.
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// Create a new form-data header with the provided field name and file name.
	// Determine Content-Type of the file by its extension.
	h := textproto.MIMEHeader{}
	h.Set("Content-Disposition", fmt.Sprintf(
		`form-data; name="%s"; filename="%s"`,
		escapeQuotes(fieldname),
		escapeQuotes(filepath.Base(filename)),
	))
	h.Set("Content-Type", "application/octet-stream")
	if ct := mime.TypeByExtension(filepath.Ext(filename)); ct != "" {
		h.Set("Content-Type", ct)
	}
	part, err := writer.CreatePart(h)
	if err != nil {
		panic(err)
	}

	// Copy the content of the file we have opened not reading the whole
	// file into memory.
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}
}
开发者ID:jemkzheng,项目名称:revel,代码行数:32,代码来源:testsuite.go

示例10: Send

// Send does what it is supposed to do.
func (m *Mail) Send(host string, port int, user, pass string) error {

	// validate from address
	from, err := mail.ParseAddress(m.From)
	if err != nil {
		return err
	}

	// validate to address
	to, err := mail.ParseAddress(m.To)
	if err != nil {
		return err
	}

	// set headers for html email
	header := textproto.MIMEHeader{}
	header.Set(textproto.CanonicalMIMEHeaderKey("from"), from.Address)
	header.Set(textproto.CanonicalMIMEHeaderKey("to"), to.Address)
	header.Set(textproto.CanonicalMIMEHeaderKey("content-type"), "text/html; charset=UTF-8")
	header.Set(textproto.CanonicalMIMEHeaderKey("mime-version"), "1.0")
	header.Set(textproto.CanonicalMIMEHeaderKey("subject"), m.Subject)

	// init empty message
	var buffer bytes.Buffer

	// write header
	for key, value := range header {
		buffer.WriteString(fmt.Sprintf("%s: %s\r\n", key, value[0]))
	}

	// write body
	buffer.WriteString(fmt.Sprintf("\r\n%s", m.HTML))

	// send email
	addr := fmt.Sprintf("%s:%d", host, port)
	auth := smtp.PlainAuth("", user, pass, host)
	return smtp.SendMail(addr, auth, from.Address, []string{to.Address}, buffer.Bytes())
}
开发者ID:dulumao,项目名称:email,代码行数:39,代码来源:email.go

示例11: Bytes

// Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
func (m *Message) Bytes() ([]byte, error) {
	// TODO: better guess buffer size
	buff := bytes.NewBuffer(make([]byte, 0, 4096))

	headers := m.msgHeaders()
	w := multipart.NewWriter(buff)
	// TODO: determine the content type based on message/attachment mix.
	headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
	headerToBytes(buff, headers)
	io.WriteString(buff, "\r\n")

	// Start the multipart/mixed part
	fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
	header := textproto.MIMEHeader{}
	// Check to see if there is a Text or HTML field
	if len(m.Content) > 0 {
		subWriter := multipart.NewWriter(buff)
		// Create the multipart alternative part
		header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
		// Write the header
		headerToBytes(buff, header)
		// Create the body sections
		if len(m.Content) > 0 {
			header.Set("Content-Type", fmt.Sprintf("%s; charset=UTF-8", m.ContentType))
			header.Set("Content-Transfer-Encoding", "quoted-printable")
			if _, err := subWriter.CreatePart(header); err != nil {
				return nil, err
			}
			// Write the text
			if err := quotePrintEncode(buff, []byte(m.Content)); err != nil {
				return nil, err
			}
		}

		if err := subWriter.Close(); err != nil {
			return nil, err
		}
	}
	// Create attachment part, if necessary
	for _, a := range m.Attachments {
		ap, err := w.CreatePart(a.Header)
		if err != nil {
			return nil, err
		}
		// Write the base64Wrapped content to the part
		base64Wrap(ap, a.Content)
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buff.Bytes(), nil
}
开发者ID:nanjishidu,项目名称:going,代码行数:53,代码来源:messge.go

示例12: renderPartsToWriter

func renderPartsToWriter(parts cloudInitParts, writer io.Writer) error {
	mimeWriter := multipart.NewWriter(writer)
	defer mimeWriter.Close()

	// we need to set the boundary explictly, otherwise the boundary is random
	// and this causes terraform to complain about the resource being different
	if err := mimeWriter.SetBoundary("MIMEBOUNDARY"); err != nil {
		return err
	}

	writer.Write([]byte(fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\n", mimeWriter.Boundary())))
	writer.Write([]byte("MIME-Version: 1.0\r\n"))

	for _, part := range parts {
		header := textproto.MIMEHeader{}
		if part.ContentType == "" {
			header.Set("Content-Type", "text/plain")
		} else {
			header.Set("Content-Type", part.ContentType)
		}

		header.Set("MIME-Version", "1.0")
		header.Set("Content-Transfer-Encoding", "7bit")

		if part.Filename != "" {
			header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, part.Filename))
		}

		if part.MergeType != "" {
			header.Set("X-Merge-Type", part.MergeType)
		}

		partWriter, err := mimeWriter.CreatePart(header)
		if err != nil {
			return err
		}

		_, err = partWriter.Write([]byte(part.Content))
		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:paultyng,项目名称:terraform,代码行数:45,代码来源:datasource_cloudinit_config.go

示例13: Bytes

// Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
func (e *Email) Bytes() ([]byte, error) {
	buff := &bytes.Buffer{}
	w := multipart.NewWriter(buff)
	// Set the appropriate headers (overwriting any conflicts)
	// Leave out Bcc (only included in envelope headers)
	e.Headers.Set("To", strings.Join(e.To, ","))
	if e.Cc != nil {
		e.Headers.Set("Cc", strings.Join(e.Cc, ","))
	}
	e.Headers.Set("From", e.From)
	e.Headers.Set("Subject", e.Subject)
	if len(e.ReadReceipt) != 0 {
		e.Headers.Set("Disposition-Notification-To", strings.Join(e.ReadReceipt, ","))
	}
	e.Headers.Set("MIME-Version", "1.0")
	e.Headers.Set("Content-Type", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary()))

	// Write the envelope headers (including any custom headers)
	if err := headerToBytes(buff, e.Headers); err != nil {
		return nil, fmt.Errorf("Failed to render message headers: %s", err)
	}
	// Start the multipart/mixed part
	fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
	header := textproto.MIMEHeader{}
	// Check to see if there is a Text or HTML field
	if e.Text != "" || e.HTML != "" {
		subWriter := multipart.NewWriter(buff)
		// Create the multipart alternative part
		header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
		// Write the header
		if err := headerToBytes(buff, header); err != nil {
			return nil, fmt.Errorf("Failed to render multipart message headers: %s", err)
		}
		// Create the body sections
		if e.Text != "" {
			header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
			header.Set("Content-Transfer-Encoding", "quoted-printable")
			if _, err := subWriter.CreatePart(header); err != nil {
				return nil, err
			}
			// Write the text
			if err := quotePrintEncode(buff, e.Text); err != nil {
				return nil, err
			}
		}
		if e.HTML != "" {
			header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
			header.Set("Content-Transfer-Encoding", "quoted-printable")
			if _, err := subWriter.CreatePart(header); err != nil {
				return nil, err
			}
			// Write the text
			if err := quotePrintEncode(buff, e.HTML); err != nil {
				return nil, err
			}
		}
		if err := subWriter.Close(); err != nil {
			return nil, err
		}
	}
	// Create attachment part, if necessary
	for _, a := range e.Attachments {
		ap, err := w.CreatePart(a.Header)
		if err != nil {
			return nil, err
		}
		// Write the base64Wrapped content to the part
		base64Wrap(ap, a.Content)
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buff.Bytes(), nil
}
开发者ID:rayleyva,项目名称:email,代码行数:75,代码来源:email.go

示例14: DecodeImageReader

// Send a multipart/related POST request to OpenOCR API endpoint to decode image data
func (c HttpClient) DecodeImageReader(imageReader io.Reader, ocrRequest OcrRequest) (string, error) {

	// create JSON for POST reqeust
	jsonBytes, err := json.Marshal(ocrRequest)
	if err != nil {
		return "", err
	}

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	mimeHeader := textproto.MIMEHeader{}
	mimeHeader.Set("Content-Type", "application/json")

	part, err := writer.CreatePart(mimeHeader)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Unable to create json multipart part")
		return "", err
	}

	_, err = part.Write(jsonBytes)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Unable to write json multipart part")
		return "", err
	}

	partHeaders := textproto.MIMEHeader{}

	// TODO: pass these vals in instead of hardcoding
	partHeaders.Set("Content-Type", "image/png")
	partHeaders.Set("Content-Disposition", "attachment; filename=\"attachment.txt\".")

	partAttach, err := writer.CreatePart(partHeaders)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Unable to create image multipart part")
		return "", err
	}

	_, err = io.Copy(partAttach, imageReader)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Unable to write image multipart part")
		return "", err
	}

	err = writer.Close()
	if err != nil {
		logg.LogTo("OCRCLIENT", "Error closing writer")
		return "", err
	}

	// create a client
	client := &http.Client{}

	// create POST request
	apiUrl := c.OcrApiFileUploadEndpointUrl()
	req, err := http.NewRequest("POST", apiUrl, bytes.NewReader(body.Bytes()))
	if err != nil {
		logg.LogTo("OCRCLIENT", "Error creating POST request")
		return "", err
	}

	// set content type
	contentType := fmt.Sprintf("multipart/related; boundary=%q", writer.Boundary())
	req.Header.Set("Content-Type", contentType)

	// TODO: code below is all duplicated with DecodeImageUrl()

	// send POST request
	resp, err := client.Do(req)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Error sending POST request")
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		return "", fmt.Errorf("Got error status response: %d", resp.StatusCode)
	}

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logg.LogTo("OCRCLIENT", "Error reading response")
		return "", err
	}

	return string(respBytes), nil

}
开发者ID:movermeyer,项目名称:open-ocr-client,代码行数:88,代码来源:ocr_http_client.go

示例15: WriteTo

func (e *Email) WriteTo(w io.Writer) (int64, error) {
	wc := &writeCounter{w: w}
	w = wc
	mpw := multipart.NewWriter(wc)

	// Write top-level headers.
	headers := e.Header
	headers.Set("Content-Type", fmt.Sprintf(`multipart/alternative; boundary="%s"`, mpw.Boundary()))
	headers.Set("MIME-Version", "1.0")
	for k, vv := range headers {
		for _, v := range vv {
			if _, err := fmt.Fprintf(w, "%s: %s\n", k, v); err != nil {
				return wc.n, err
			}
		}
	}
	if _, err := fmt.Fprintln(w); err != nil {
		return wc.n, err
	}

	// Write text part.
	textHeader := textproto.MIMEHeader{}
	textHeader.Set("Content-Type", `text/plain; charset="utf-8"; format="fixed"`)
	textHeader.Set("Content-Transfer-Encoding", "quoted-printable")
	pw, err := mpw.CreatePart(textHeader)
	if err != nil {
		return wc.n, fmt.Errorf("create text part: %s", err)
	}
	qpw := quotedprintable.NewWriter(pw)
	if _, err := qpw.Write(e.Text); err != nil {
		return wc.n, fmt.Errorf("write text part: %s", err)
	}
	if err := qpw.Close(); err != nil {
		return wc.n, fmt.Errorf("close text part: %s", err)
	}

	// Write top-level HTML multipart/related headers.

	// Chicken-and-egg: we need the inner multipart boundary to write the outer
	// part headers, but we can't get the boundary until we've constructed
	// multipart.Writer with a part writer. We'll generate the boundary ahead
	// of time and then manually supply it to the inner multipart.Writer.
	htmlRelatedBoundary := multipart.NewWriter(nil).Boundary()

	htmlRelatedHeader := textproto.MIMEHeader{}
	htmlRelatedHeader.Set("Content-Type", fmt.Sprintf(`multipart/related; boundary="%s"`, htmlRelatedBoundary))
	htmlRelatedHeader.Set("MIME-Version", "1.0")
	pw, err = mpw.CreatePart(htmlRelatedHeader)
	if err != nil {
		return wc.n, fmt.Errorf("create html multipart part: %s", err)
	}

	// Create inner multipart data for HTML with attachments.
	htmlmpw := multipart.NewWriter(pw)
	htmlmpw.SetBoundary(htmlRelatedBoundary)
	if err != nil {
		return wc.n, fmt.Errorf("set html multipart boundary: %s", err)
	}

	// Write html part.
	htmlHeader := textproto.MIMEHeader{}
	htmlHeader.Set("Content-Type", `text/html; charset="utf-8"`)
	htmlHeader.Set("Content-Transfer-Encoding", "quoted-printable")
	htmlpw, err := htmlmpw.CreatePart(htmlHeader)
	if err != nil {
		return wc.n, fmt.Errorf("create html part: %s", err)
	}
	qpw = quotedprintable.NewWriter(htmlpw)
	if _, err := qpw.Write(e.HTML); err != nil {
		return wc.n, fmt.Errorf("write html part: %s", err)
	}
	if err := qpw.Close(); err != nil {
		return wc.n, fmt.Errorf("close html part: %s", err)
	}

	// Write attachments.
	for _, att := range e.Attachments {
		attHeader := textproto.MIMEHeader{}
		attHeader.Set("Content-ID", fmt.Sprintf("<%s>", att.ContentID))
		attHeader.Set("Content-Type", mime.TypeByExtension(filepath.Ext(att.Name)))
		attHeader.Set("Content-Transfer-Encoding", "base64")
		attHeader.Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, att.Name))
		htmlpw, err := htmlmpw.CreatePart(attHeader)
		if err != nil {
			return wc.n, fmt.Errorf("create attachment %s: %s", att.Name, err)
		}
		b64w := base64.NewEncoder(base64.StdEncoding, htmlpw)
		if _, err := b64w.Write(att.Content); err != nil {
			return wc.n, fmt.Errorf("write attachment %s: %s", att.Name, err)
		}
		if err := b64w.Close(); err != nil {
			return wc.n, fmt.Errorf("close attachment %s: %s", att.Name, err)
		}
	}

	// Finalize HTML multipart/related.
	if err := htmlmpw.Close(); err != nil {
		return wc.n, fmt.Errorf("multipart close: %s", err)
	}

//.........这里部分代码省略.........
开发者ID:logan,项目名称:heim,代码行数:101,代码来源:email.go


注:本文中的net/textproto.MIMEHeader.Set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。