Sending and reading files via email with Golang

With Golang gin rest api, when a user enters the file via e-mail, it sends the file to the recipient, but when debugging, I encounter this error.

but when the user enters the form, the file is sent, why is there a file path error?

2023/03/13 17:28:46 open C:\fakepath\deneme.pdf: The system cannot find the path specified.
exit status 1

router.POST("/post", func(c *gin.Context) {
		// Get form data
		var form forms1
		if err := c.BindJSON(&form); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid form data"})
			return
		}

		// Send an email
		auth := smtp.PlainAuth("", "xxx@gmail.com", "xxx", "smtp.gmail.com")

		to := []string{"xxx@gmail.com"}
		// Read the file contents
		fileContent, err := ioutil.ReadFile(form.ChooseFile)
		if err != nil {
			log.Fatal(err)
		}

		// Encode the file contents to Base64
		encodedContent := base64.StdEncoding.EncodeToString(fileContent)

		// Attach the file to the email
		msg := []byte("To: " + strings.Join(to, ",") + "\r\n" +
			"Subject: JobApply Form Submission\r\n" +
			"MIME-version: 1.0;\r\n" +
			"Content-Type: multipart/mixed; boundary=\"boundary123\"\r\n" +
			"\r\n" +
			"--boundary123\r\n" +
			"Content-Type: text/plain; charset=utf-8\r\n" +
			"\r\n" +
			"--boundary123\r\n" +
			"Content-Type: application/octet-stream\r\n" +
			"Content-Transfer-Encoding: base64\r\n" +
			"Content-Disposition: attachment; filename=\"" + filepath.Base(form.ChooseFile) + "\"\r\n" +
			"\r\n" +
			encodedContent + "\r\n" +
			"--boundary123--")

		if err := smtp.SendMail("smtp.gmail.com:587", auth, "xxx@gmail.com", to, []byte(msg)); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to send email"})
			return
		}

		// Send successful response
		c.JSON(http.StatusOK, gin.H{"status": "success"})
	})

	// start server
	if err := router.Run(":8070"); err != nil {
		panic(err)
	}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.